使用partials,如何以DRY方式呈现`striped`表格行?

mar*_*ion 3 ruby-on-rails partial-views ruby-on-rails-3

所以我有一些看起来像这样的视图代码:

<div class="box-content">
    <table class="table table-properties">
        <tbody>             
            <%= render :partial => 'property', collection: @search.listings, as: :listing %>
        </tbody>
    </table>                                
</div>
Run Code Online (Sandbox Code Playgroud)

在那_property.html.erb,我有这个:

<tr>
    <td class="span2">
        <%= link_to listing_path(listing), :class => "thumbnail thumb2" do %>
            <%= image_tag "room_1.jpg", :alt => "Lucas" %>
        <% end %>
    </td>
    <td>
        <h2><%= link_to listing.headline, listing_path(listing) %></h2>
        <h5><%= listing.listing_type.name if listing.listing_type "#{listing.neighborhood.name.capitalize}" %></h5>
        <h5>Maintenance <%= number_to_currency(listing.maintenance) %></h5>
    </td>
    <td class="span1">
        <h2 class="price"><%= number_to_currency(listing.price)%></h2>
        <h5><%= "#{listing.num_bedrooms} bed, #{listing.num_bathrooms} bath" %></h5>
    </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

基本上,我想准确地生成上面的代码,对于每一行,唯一的区别是我希望每第2行(即所有偶数行)都具有class=striped..ie <tr class=striped>.

关于如何以干燥的方式做到这一点的想法?

pdu*_*ler 11

你已经尝试使用cyclecurrent_cycle

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-cycle

<tr class="<%= cycle('odd', 'even') -%>">
  <!-- etc -->
</tr>
Run Code Online (Sandbox Code Playgroud)

这会使您odd和您的班级交替使用,even并且在渲染集合时恕我直言也应该工作.如果你需要多次实际循环的值,你可以得到它current_cycle(因为cycle多次调用会扰乱你的循环,除非你想要它).