Quick Zebra Striping in Rails 3

Posted by jake Sun, 12 Aug 2007 08:57:00 GMT

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

Comments

Leave a response

  1. Avatar
    rod 1 day later:

    Sweet as it is! thanks!

  2. Avatar
    Roman Mackovcak 1 day later:

    Nice piece of code. Thanks for the tip.

  3. Avatar
    herval 1 day later:

    a new Rails discovery every day… :-)

Comments