Question

I am rendering a rails partial and I want to alternate the background color when it renders the partial. I know that is not super clear so here is an example of what I want to do:

Row One grey Background Row Two yellow background Row Three grey Background Row Four yellow background
  • sorry stackoverflow seams to prevent the background colors from being shown but I think this makes my idea clear

This is the view code that I am using

<table>
  <%= render :partial => 'row' :collection => @rows %>
</table>

the _row.html.erb partial looks like this

<tr bgcolor="#AAAAAA">
  <td><%= row.name %></td>
</tr>

The problem is I do not know how to change the background color for every other row. Is there a way to do this?

Was it helpful?

Solution

You could use the Cycle helper. Something like this:

<tr class="<%= cycle("even", "odd") %>">
  <td><%= row.name %></td>
</tr>

Or in your case use bgcolor instead, although i would recomend using css classes.

You can cycle through more than two values: cycle(‘first’, ‘second’, ‘third’, ‘and_more’).

There is also: reset_cycle(‘cycle_name’) This makes sure that on each iteration, you will start again with your first value of the cycle list.

Check the rails documentation for more examples.

OTHER TIPS

Another idea, you can use javascript to change the element's style based on (total number of TD's % 2).

That way all your visual stuff are contained in html/css/javascript layer. Then again, this technique does not work if javascript is disabled.

There is one "gotcha" with cycle: If you should append to the string, the cycle breaks. For example,

cycle('odd', 'even') << " some other classes"

will break the cycle. However, reversing the order or constructing a string works fine:

"some other classes " << cycle('odd', 'even')
"#{cycle('odd', 'even')} some other classes"

I've not (yet) delved into the source to see why this may be so. Also, I'm using Rails 3.2.x

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top