开发者

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

开发者 https://www.devze.com 2023-01-19 20:02 出处:网络
Desired Output: <ul> <li class=\"odd\">stuff</li> <li class=\"even\">stuff</li>

Desired Output:

<ul>
 <li class="odd">stuff</li>
 <li class="even">stuff</li>
 <li class="开发者_StackOverflowodd">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


The Rails Way to do this is to use cycle.

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

Documentation


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;
}


Strictly speaking not really rails but a clean way achieving odd/even is with jquery on the client side: http://api.jquery.com/odd-selector/


Rails' TextHelper method: cycle.

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

Note: 'odd' should come before 'even' (not as listed above) or your designer might not be happy that the starting background-color didn't go as she planned.

0

精彩评论

暂无评论...
验证码 换一张
取 消