Reputation: 1901
How can I display results from an object into columns like the following:
<ul>
<li><a href="#">Category name</a></li>
<li><a href="#">Category name</a></li>
<li><a href="#">Category name</a></li>
</ul>
<ul>
<li><a href="#">Category name</a></li>
<li><a href="#">Category name</a></li>
<li><a href="#">Category name</a></li>
</ul>
<ul>
<li><a href="#">Category name</a></li>
<li><a href="#">Category name</a></li>
<li><a href="#">Category name</a></li>
</ul>
Regardless of results returned to @categories = Category.all
I want to divide them up into three columns like this. What's the best way programmatically to do it?
Upvotes: 2
Views: 1566
Reputation: 16345
each_slice method can help you
%w(a s d f g h).each_slice(3) {|x| p x}
["a", "s", "d"]
["f", "g", "h"]
In HAML, you can handle it by this way
- cats = Array.new(3, [])
= @categories.each_slice(3) do |category|
- cats = cats.zip(category).map(&:flatten)
- cats.each do |subcat|
%ul
- subcat.each do |l|
%li
%a{:href => "#"}
= l
Upvotes: 8
Reputation: 27473
Rails has a dedicated way to do that using in_groups:
<% @categories.in_groups(3, false) do |group| %>
<ul>
<% group.each do |category| %>
<li><%= category.name %></li>
<% end %>
</ul>
<% end %>
The second argument of in_groups (which is false in this case) means that this code won't produce empty list items if @categories.size isn't a multiple of 3.
Upvotes: 8