Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - Building a Table, Want to Alternate colors every row

Desired Output:

<ul>
 <li class="odd">stuff</li>
 <li class="even">stuff</li>
 <li class="odd">stuff</li>
 <li class="even">stuff</li>
 <li class="odd">stuff</li>
 <li class="even">stuff</li>
 <li class="odd">stuff</li>
 <li class="even">stuff</li>
</ul>

CSS:

.odd {color:blue}
.even{color:red;}

In rails 3 is there a clean way to do this without counters etc?

thanks

like image 394
AnApprentice Avatar asked Oct 08 '10 23:10

AnApprentice


2 Answers

The Rails Way to do this is to use cycle.

<li class="<%= cycle('even', 'odd') -%>">stuff</li>

Documentation

like image 146
Raphomet Avatar answered Oct 06 '22 00:10

Raphomet


I found an answer here that worked for me, here fleshed out a bit. Tested to work with Rails 3.2.8.

The something.html.erb file:

<table>
  <tr>
    <th>foo</th>
    <th>bar</th>
  </tr>
  <% @something.each do |s| -%>
    <tr class="<%= cycle('oddrow', 'evenrow') -%>">
      <td> ... </td>
      <td> ... </td>
    </tr>
  <% end %>
</table>

The something.css.scss file:

table tr.oddrow {
    background-color: #111111;
}

table tr.evenrow {
    background-color: #333333;
}
like image 45
Teemu Leisti Avatar answered Oct 06 '22 00:10

Teemu Leisti