Quick Zebra Striping in Rails

Posted by admin 12/08/2007 at 08h57

Striping table rows is usually a necessity when making accessible web pages. This can be a tedious task. Through the ages (and by ages I mean the last 10 years or so) there have been many ways to do this in many dynamic languages. Everything from taking the modulo of the index when iterating through the set, to flipping a counter back and forth.

Well, if you’re programming in rails, you get a much easier way to do it via the cycle method. Let me show you how easy it is:

<table>
  <% @objects.each do |obj| %>
  <tr class="<%= cycle("even", "odd") %>">
    <td><%= obj.id %></td>
    <td><%= obj.title %></td>
  <tr>
  <% end %>
</table>

Simplicity itself. Now as you loop through the set, it will cycle the class name of the row between “even” and “odd”. Now all you need to do is set CSS values for those classes and your done.

Here is a quick example of a CSS class for odd:


.odd{
background:#dedede;
}

Gotta love rails.

—jake