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>
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 %>
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With