I have a loop for my Activity model
<% @activities.each do |activity| %>
<div>
<div class="cell">
<%= image_tag(activity.image) %>
</div>
<div class="cell">
<h4><%= activity.title %></h4>
<p><%= activity.description %></p>
<span><%= activity.distance %></span>
</div>
</div>
<% end %>
I want to create a zig-zag effect, so I need to re-arrange the HTML for every even activity, so the markup will look like this:
<div>
<div class="cell">
<h4><%= activity.title %></h4>
<p><%= activity.description %></p>
<span><%= activity.distance %></span>
</div>
<div class="cell">
<%= image_tag(activity.image) %>
</div>
</div>
Is there a way to do this with an if statement? Something like this:
<% if activity.odd? %>
<% @activities.each do |activity| %>
<div>
<div class="cell">
<%= image_tag(activity.image) %>
</div>
<div class="cell">
<h4><%= activity.title %></h4>
<p><%= activity.description %></p>
<span><%= activity.distance %></span>
</div>
</div>
<% end %>
<% else %>
<% @activities.each do |activity| %>
<div>
<div class="cell">
<h4><%= activity.title %></h4>
<p><%= activity.description %></p>
<span><%= activity.distance %></span>
</div>
<div class="cell">
<%= image_tag(activity.image) %>
</div>
</div>
<% end %>
There are a few ways to do this.
The first and best way is to do this with CSS’s
nth-childselector, assuming it’s possible to achieve your desired effect purely through CSS. Usenth-child(odd)ornth-child(even), as described in Alternate table row color using CSS?If you’re iterating over a collection using
.each, you can add a.with_indexand check whether the index is odd or even:Note that by default the index is zero-based, so your first element will be considered “even”. You can pass a starting index of
1towith_indexif you want the alternating to start odd instead:An alternative to using
with_indexis to use Rails’cyclehelper, which “magically” returns the next argument in rotation each time its invoked:Also note that this is a fantastic opportunity for refactoring. You should distill the two reused
celldivs into their own partials and render them in the order you want: