每3个项目新增一行

时间:2013-01-25 19:22:32

标签: ruby-on-rails ruby

我想一次渲染我的项目列表3,以便它们以三行的形式输出。我目前正在使用

<div class="row">
  <div class="three columns">
 <% @items.each do |f|%>
   <div class="item">
     <%= f.content %>
       </div>
     <% end %>
  </div>
</div>

输出一行'行'中的所有规则 -

<div class="row">
  <div class="three columns">
   <div class="item">
     This is the content
       </div>
       <div class="item">
     This is the content
       </div>
       <div class="item">
     This is the content
       </div>
       <div class="item">
     This is the content
       </div>
       <div class="item">
     This is the content
       </div>
  </div>
</div>

我希望能够做的是为返回的每三个项输出一行,所以 -

<div class="row">
  <div class="three columns">
   <div class="item">
     This is the content
       </div>
       <div class="item">
     This is the content
       </div>
       <div class="item">
     This is the content
       </div>
  </div>
</div>
<div class="row">
  <div class="three columns">
   <div class="item">
     This is the content
       </div>
       <div class="item">
     This is the content
       </div>
       <div class="item">
     This is the content
       </div>
  </div>
</div>

由于

2 个答案:

答案 0 :(得分:40)

除了前面提到的each_slice之外,Rails还有一个in_groups_of方法,您可以这样使用:

<% @items.in_groups_of(3, false).each do |group| %>
  <div class="row">
    <div class="three columns">
      <% group.each do |item| %>
        <div class="item">
          <%= item.content %>
        </div>
      <% end %>
    </div>
  </div>
<% end %>

each_slice几乎相同,除了需要输出空白div的场景变得更加清晰如此:

<% @items.in_groups_of(3).each do |group| %>
  <div class="row">
    <div class="three columns">
      <% group.each do |item| %>
        <div class="item">
          <%= item.content if item %>
        </div>
      <% end %>
    </div>
  </div>
<% end %>

in_groups_of默认使用nil填充最后一个组中的项目,因此它将进行最后几次迭代,if item检查将确保它不会爆炸在content上调用nil

in_groups是另一种用于视图格式化的有趣工具。

答案 1 :(得分:11)

您可以使用each_slice方法:

<% @items.each_slice(3) do |array_of_3_items|%>
  <div class="row">
    <div class="three columns">
      <% array_of_3_items.each do |item|%>
        <div class="item">
          <%= item.content %>
        </div>
      <% end %>
    </div>
  </div>
<% end %>

附加说明:如果您想要最后一行的3个div,即使最后一行只包含2个项目,该怎么办? (即@items是5个项目的列表,最后一行应该只输出2个div。“

解决方案:

<% @items.each_slice(3) do |array_of_3_items|%>
  <div class="row">
    <div class="three columns">
      <% array_of_3_items.each do |item|%>
        <div class="item">
          <%= item.content %>
        </div>
      <% end %>
      <% (3 - array_of_3_items.length).times.each do |fake_div| %>
        <div class="item empty">
        </div>
      <% end %>
    </div>
  </div>
<% end %>