Iterating over ‘posts’ I want to create a row div which will contain two post divs:
<div id="row">
<div id="post"> ... </div>
<div id="post"> ... </div>
</div>
<div id="row">
<div id="post"> ... </div>
<div id="post"> ... </div>
</div>
If I try this:
- @posts.each_with_index do |post,index|
- if index %2 == 0
.row
.post
- else
.post
…then I get:
<div class="row">
<div class="post"></div>
</div>
<div class="post"></div>
<div class="row">
<div class="post"></div>
</div>
<div class="post"></div>
I can see why this happens but I can’t figure out how to do it correctly. Any ideas?
UPDATE:
When accessing object attributes as per apneadiving’s suggesion, I receive errors when the last slice contains only a single post. For example, the following…
- @posts.each_slice(2) do |post1, post2|
.row
.post= post1.title
.post= post2.title
returns the error “undefined method `title’ for nil:NilClass” when there are an odd number of posts. To get around this I have used this:
- @posts.each_slice(2) do |post1, post2|
.row
.post= post1.title
.post= post2.title unless post2.nil?
I’d take my posts 2 by 2, I can’t see how to do otherwise with haml: