Wednesday, April 5, 2006

More Zebras

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:

  1. rails has a cycle command that does this too...
    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000515

    ReplyDelete
  2. Nice, but why would you write one rather than using the already available 'cycle' helper?
    http://rubyonrails.org/api/classes/ActionView/Helpers/TextHelper.html#M000515
    Unless, of course, that you use the index within your loop block :)

    ReplyDelete
  3. Another nice way to do this is using the cycle helper
    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000515
    ">

    ReplyDelete
  4. Why not use the built-in text helper cycle() ?
    ">

    ReplyDelete
  5. Ooops, input not escaped :
    <tr class="<%= cycle("even", "odd") %>">

    ReplyDelete
  6. 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...

    ReplyDelete
  7. 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