Besides the aforementioned each_slice
, Rails also has an in_groups_of method that you can use like so:
<% @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 %>
Pretty much the same as each_slice
, except the scenario of needing to output blank divs becomes much cleaner like so:
<% @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
pads missing items in the last group with nil
by default, so it will make the last few iterations and the if item
check will make sure it doesn't blow up by calling content
on nil
.
in_groups is another fun one to use for view formatting.