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.
精彩评论