mattmccray

 
« Not-So New Theme | Home | Rails Theme Support P… »

More Zebras

» Published April 05, 2006 under Rails, Software

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>
Here's the helper I've been using lately for zebra striping table rows:
def zebra_stripe( index, even_class="Even", odd_class="Odd" )
  index % 2 == 0 ? even_class : odd_class
end
In 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!

7 comments

04.06.06 @ 01:30 robert said...
rails has a cycle command that does this too… http://api.rubyonrails.org/classes/Actio..
04.06.06 @ 01:39 Paul said...
Nice, but why would you write one rather than using the already available ‘cycle’ helper? http://rubyonrails.org/api/classes/Actio..

Unless, of course, that you use the index within your loop block :)
04.06.06 @ 03:21 Darragh Curran said...
Another nice way to do this is using the cycle helper
http://api.rubyonrails.org/classes/Actio..

“>
04.06.06 @ 04:00 Ned Baldessin said...
Why not use the built-in text helper cycle() ?

“>
04.06.06 @ 04:01 Ned Baldessin said...
Ooops, input not escaped :

<tr class="<%= cycle("even", "odd") %>">
04.06.06 @ 13:38 M@ said...
LOL

I love the Rails community. Very quick responses.

Yes, you are all right. I just missed the cycle helper!

Oh the shame of it…
04.07.06 @ 09:56 topfunky said...
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.

No trackbacks

Trackback link:

Please enable javascript to generate a trackback url


You may use Textile, or simple html tags (B,I). Feel free to use Emoticons too. Oh, and please limit yourself to only five links per comment. Anything more and you'll probably get detained by the spam police.