user1049097
user1049097

Reputation: 1901

How to divide data into columns with Rails 3?

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

Answers (2)

evfwcqcg
evfwcqcg

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

Damien
Damien

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

Related Questions