tybro0103
tybro0103

Reputation: 49693

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>

Upvotes: 8

Views: 1893

Answers (3)

tybro0103
tybro0103

Reputation: 49693

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()

Upvotes: 3

lightswitch05
lightswitch05

Reputation: 9428

Sounds like a great chance to use a modulus

<div class="row">
<% for(i=1, i<[email protected], i++ %>
    <% if i%4 == 0 %>
        </div>
        <div class="row">
    <% end %>
    <div class="member"><%=@members[i-1]%></div>
<% end %>
</div>

Upvotes: 0

HargrimmTheBleak
HargrimmTheBleak

Reputation: 2167

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 %>

Upvotes: 17

Related Questions