Search code examples
ruby-on-railscsscycle

Rails CSS zebra-striping rows, but in sets of three


What I know: Rails has the cycle() method that enables odd/even rows in a table to have different CSS classes. We can pass multiple classes to the cycle() method and that works great.

I wanted rows which are grouped in three's; so, I used this:

...some html-table  code...
<tr class="<%= cycle("table_row_1","table_row_2","table_row_3","table_row_4","table_row_5","table_row_6") %>">
...some more html-table  code...

The corresponding CSS I defined is:

.table_row_1 { background-color: red;}
.table_row_2 { background-color: red;}
.table_row_3 { background-color: red;}
.table_row_4 { background-color: blue;}
.table_row_5 { background-color: blue;}
.table_row_6 { background-color: blue;}

It works, but it doesn't feel "clean".

Is there a recommended way to do this in Rails ?

UPDATES

  1. On similar lines to @Ryan Bigg's answer, is it possible to generate strings in sequence so that the cycle() method can be sent strings of the form prefix_1 prefix_2 prefix_3 somehow using the *3 syntax or some other way?
  2. The inspiration to use this "every third row" striping came from an article on Edward Tufte's site
  3. It seems CSS3 can do this (link), but that's not widely supported at this time :(
  4. Not related to question, but I just searched for this problem I have on Google, and the questions listed at questionhub.com! I never asked this on questionhub.com!
  5. Now its on http://loopingrecursion.com too! What's going on.

Solution

  • How about this?

    <tr class="<%= cycle(*[["striped"]*3,["unstriped"]*3].flatten) %>">