开发者

Rails 3 - Building a Table, Want to Alternate colors every row

Desired Output:

<ul>
 <li class="odd">stuff</li>
 <li class="even">stuff</li>
 <li class="开发者_StackOverflowodd">stuff</li>
 <li class="even">stuff</li>
 <li class="odd">stuff</li>
 <li class="even">stuff</li>
 <li class="odd">stuff</li>
 <li class="even">stuff</li>
</ul>

CSS:

.odd {color:blue}
.even{color:red;}

In rails 3 is there a clean way to do this without counters etc?

thanks


The Rails Way to do this is to use cycle.

<li class="<%= cycle('even', 'odd') -%>">stuff</li>

Documentation


I found an answer here that worked for me, here fleshed out a bit. Tested to work with Rails 3.2.8.

The something.html.erb file:

<table>
  <tr>
    <th>foo</th>
    <th>bar</th>
  </tr>
  <% @something.each do |s| -%>
    <tr class="<%= cycle('oddrow', 'evenrow') -%>">
      <td> ... </td>
      <td> ... </td>
    </tr>
  <% end %>
</table>

The something.css.scss file:

table tr.oddrow {
    background-color: #111111;
}

table tr.evenrow {
    background-color: #333333;
}


Strictly speaking not really rails but a clean way achieving odd/even is with jquery on the client side: http://api.jquery.com/odd-selector/


Rails' TextHelper method: cycle.

<li class="<%= cycle('odd','even') -%>">stuff</li>

Note: 'odd' should come before 'even' (not as listed above) or your designer might not be happy that the starting background-color didn't go as she planned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜