Zebra-striped tables using Rails

Zebra-striped tables are tables where row colors alternate between a light color and a dark color and can be done both using server-side code (ie. Rails) or client-side code (ie. JavaScript). I posted a question asking for the most convenient way to create zebra-striped tables to the Rails newsgroup some weeks ago and the responses I received were actually quite scathing. I’ve normally done this type of thing using server-side code when working with other programming languages (ASP, PHP, JSP, ColdFusion, etc.), but many people feel that this is an extreme no-no (and aren’t afraid to tell anyone that’ll listen to them), as it muddles up the separation of business logic from presentation.

Anyway, my point is that, regardless of what others think, I want to continue doing this type of design using server-side code and a recent post on the Code Snippets website highlights a Rails helper tag called cycle that makes this very convenient. (The name will be familiar for those that have used the Smarty templating engine for PHP.) The cycle tag is exactly the type of suggestion I was looking for when I posted my initial question to the newsgroup. Before that, I’d been using some nasty combination of if statements and the mod operator to determine the row color and that had completely uglified my code.

This is how you use the cycle helper method:
<tr class="<%= cycle("even", "odd") %>">
... use item ...
</tr>

You can read more about the cycle helper method in the Rails API.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *