Alternating Colors in Ruby/Rails

By Shahram Javey

Alternate Colors For displaying lists it is often useful to show the rows of the list in alternating colors. Ruby on Rails makes this really easy.

  1. Define the background colors using HTML style tag.
  2. <head>
    <style>
    .even { background: #99ccff; }
    .odd { background: #cccccc; }

    </style>
    </head>

  3. Add the class attribute that calls the cycle method to the HTML element that you use to describe the row, e.g., DIV or table row TR, …, for example:

    <% for track in @tracks %>
    <div class="<%= cycle('even','odd') %>" >
    <h3> 'show', :id => track %></h3>
    </div>
    <% end %>

That is it. Kudos to Ruby on Rails creators for making this so simple!

3 Responses to “Alternating Colors in Ruby/Rails”

  1. Tobias Hoellrich Says:

    Where does the “cycle” come from? Is that a Rails-builtin?

  2. sj Says:

    Rails defines a framework in terms of APIs. It includes a template engine (similar to Java JSP), e.g. The APIs includes a number of very useful utility classes. One of them is called ActionView::Helpers::TextHelper and it includes a method called cycle.

  3. Josh Says:

    perfect! i was using my own helper, no sense reinventing the wheel. -thanks!

Leave a Reply