每3件新行

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

哪个输出所有规则在一个’行’ –

 
This is the content
This is the content
This is the content
This is the content
This is the content

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

 
This is the content
This is the content
This is the content
This is the content
This is the content
This is the content

谢谢

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

 <% @items.in_groups_of(3, false).each do |group| %> 
<% group.each do |item| %>
<%= item.content %>
<% end %>
<% end %>

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

 <% @items.in_groups_of(3).each do |group| %> 
<% group.each do |item| %>
<%= item.content if item %>
<% end %>
<% end %>

in_groups_of默认情况下in_groups_of最后一个组中缺少nil的项目,因此它将进行最后几次迭代, if item检查将确保它不会通过调用nil上的content而爆炸。

in_groups是另一个用于视图格式的有趣的。

您可以使用each_slice方法:

 <% @items.each_slice(3) do |array_of_3_items|%> 
<% array_of_3_items.each do |item|%>
<%= item.content %>
<% end %>
<% end %>

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

解决方案:

 <% @items.each_slice(3) do |array_of_3_items|%> 
<% array_of_3_items.each do |item|%>
<%= item.content %>
<% end %> <% (3 - array_of_3_items.length).times.each do |fake_div| %>
<% end %>
<% end %>