Nick Gilbert Nick Gilbert - 1 month ago 19
Ruby Question

Ruby ERB Page: Render two partials side by side in a for loop

I'm new to Ruby ERB pages and am trying to use one to render my blog. Currently I have this for loop which renders one post per row on the blog page

<% @posts.each do |post| %>
<%= render :partial => 'post', :locals => {:post => post} %>
<% end %>


However, since that is a for-each loop I can't access two elements in one iteration to tell the loop to render two posts side by side on each row. How can I change this for-loop to render two posts side by side on one row?

max max
Answer

If you really had to output into two separate wrapper elements you would start by splitting the collection.

<% odd, even = arr.partition.with_index{ |_, i| i.even? } %>
<div class="column odd">
  <% odd.each do |post| %>
    <%= render :partial => 'post', :locals => {:post => post} %>
  <% end %>
</div>
<div class="column even">
  <% even.each do |post| %>
    <%= render :partial => 'post', :locals => {:post => post} %>
  <% end %>
</div>

Thats how it would have been done circa 2008 when you based your web design off a 720 or 960px width.

Nowadays this problem is better solved with CSS.

Comments