Update: OK, you got me. You should really use the built-in Rails helper, cycle
.
<table class="Grid"> <% for user in @users %> <tr class="<%= cycle('Even', 'Odd') %>"> <td> ... Stuff Here </td> </tr> <% end %> </table>
def zebra_stripe( index, even_class="Even", odd_class="Odd" ) index % 2 == 0 ? even_class : odd_class endIn the view, you use the rubyesque
.each_with_index
like this:
<table class="Grid"> <% @users.each_with_index do |user, i| %> <tr class="<%= zebra_stripe(i) %>"> <td> ... Stuff Here </td> </tr> <% end %> </table>Simple as that!
rails has a cycle command that does this too...
ReplyDeletehttp://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000515
Nice, but why would you write one rather than using the already available 'cycle' helper?
ReplyDeletehttp://rubyonrails.org/api/classes/ActionView/Helpers/TextHelper.html#M000515
Unless, of course, that you use the index within your loop block :)
Another nice way to do this is using the cycle helper
ReplyDeletehttp://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000515
">
Why not use the built-in text helper cycle() ?
ReplyDelete">
Ooops, input not escaped :
ReplyDelete<tr class="<%= cycle("even", "odd") %>">
LOL
ReplyDeleteI love the Rails community. Very quick responses.
Yes, you are all right. I just missed the cycle helper!
Oh the shame of it...
I stumbled upon cycle a while ago while looking through the API docs. It seems that there are many silent features of Rails that are useful, but don't get a lot of press.
ReplyDelete