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:

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

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:


Gotta love rails.


This entry was posted on 12/08/2007 at 08h57 and Posted in . You can follow any response to this entry through the Atom feed. You can leave a comment .

Tags , , , ,


Leave a comment