Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap every N elements in parent div in ERB (Rails)?

My members index page is simply a list of members, but I'd like every 3 members to be wrapped in a containing div (that will act like a row). So rather than:

<div class="member"></div>
<div class="member"></div>
<div class="member"></div>
<div class="member"></div>
<div class="member"></div>

I need the markup to be:

<div class="row">
  <div class="member"></div>
  <div class="member"></div>
  <div class="member"></div>
</div>
<div class="row">
  <div class="member"></div>
  <div class="member"></div>
</div>

I do have a solution, but I'm not happy with it. I have actually seen a better way to do it in ERB before, but can't find it again.

My current code:

<div class="row">
  <% @members.each do |member| %>
    <div class="member"><%=member.name%></div>
    <%= cycle("", "", "</div><div class=\"row\">".html_safe) %>
  <% end %>
</div>
like image 442
tybro0103 Avatar asked Jul 20 '12 14:07

tybro0103


2 Answers

How about this:

<% @members.each_slice(3) do |slice| %>
  <div class="row">
    <% slice.each do |member| %>
      <div class="member">
      ...your markup here
      </div>
    <% end %>
  </div>
<% end %>
like image 151
HargrimmTheBleak Avatar answered Sep 21 '22 07:09

HargrimmTheBleak


I found the method I was looking for. It's basically identical to each_slice() posted by @HargrimmTheBleak, but has a more friendly name:

in_groups_of()

like image 39
tybro0103 Avatar answered Sep 20 '22 07:09

tybro0103