Reputation: 49693
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
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:
Upvotes: 3
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
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