Blog.XDite.net

Ruby / Rails / Web Development

Rails 的 Cycle Helper 以及 CSS 中的 Nth-child

| Comments

在設計需要顏色循環的表格時你會怎麼作?

table

Rails

初入門者

使用兩種不同 HTML class : even 與 odd,上不同的顏色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<% count = 0 %>
<table>
<% @items.each do |item| %>
  <% if count % 2 == 0 %>
    <% css_class = "even "%>
  <% else %>
    <% css_class = "odd" %>
  <% end %>
  <tr class="<%= css_class %>">
    <td>item</td>
  </tr>
  <% count += 1%>
<% end %>
</table>

<% end %>

懂一點 Ruby

Ruby 裡面有 each_with_index,不需要在外部宣告 count

1
2
3
4
5
6
7
8
9
10
11
12
<table>
<% @items.each_with_index do |item, index| %>
  <% if index % 2 == 0 %>
    <% css_class = "even "%>
  <% else %>
    <% css_class = "odd" %>
  <% end %>
  <tr class="<%= css_class %>">
    <td>item</td>
  </tr>
<% end %>
</table>

熟 Rails Helper

Rails 有 cycle 這個 helper,可以做出循環效果

1
2
3
4
5
6
7
<table>
<% @items.each do |item| %>
  <tr class="<%= cycle("odd", "even") %>">
    <td>item</td>
  </tr>
<% end %>
</table>

熟 CSS

使用 pseudo class 中的 nth-child

1
2
3
4
5
6
7
<table>
<% @items.each do |item| %>
  <tr>
    <td>item</td>
  </tr>
<% end %>
</table>

用法::nth-child(an+b)

1
2
3
4
5
6
tr:nth-child(2n+1) {
  color: #ccc;
}
tr:nth-child(2n) {
  color: #000;
}

小結

快改用 nth-child,不要繼續在 class 裡面寫 even, odd, one, two, three 了 XD

Comments