For loop, wrap every two posts in a div

Tom picture Tom · Jan 4, 2014 · Viewed 16k times · Source

Basically, I am using Jekyll (which uses the Liquid templating language) and I am trying to write a for loop which wraps every two items in a div.

This is my current loop:

<div>
  {% for post in site.posts %}
    <a href="{{ post.url }}">{{ post.title }}</a>
  {% endfor %}
</div>

Which would output four posts like so:

<div>
  <a href="#">Title</a>
  <a href="#">Title</a>
  <a href="#">Title</a>
  <a href="#">Title</a>
</div>

My desired output for four posts is:

<div>
  <a href="#">Title</a>
  <a href="#">Title</a>
</div>

<div>
  <a href="#">Title</a>
  <a href="#">Title</a>
</div>

How can I accomplish this?

Answer

Christian Specht picture Christian Specht · Jan 6, 2014

If the number of <div>s and posts is fixed (which seems to be the case based on which answer you selected), there's a shorter way to get the same output - using limit and offset:
(Liquid's approach to paging)

<div>
  {% for post in site.posts limit: 2 %}
    <a href="{{ post.url }}">{{ post.title }}</a>
  {% endfor %}
</div>
<div>
  {% for post in site.posts limit: 2 offset: 2 %}
    <a href="{{ post.url }}">{{ post.title }}</a>
  {% endfor %}
</div>

Even better solution:

If the number of posts is not fixed (so when you have 100 posts, you want 50 <div>s with two posts each), then you can use forloop.index (which was already mentioned in most of the other answers), and use modulo to find out if the current index is even or odd:

{% for post in site.posts %}
  {% assign loopindex = forloop.index | modulo: 2 %}
  {% if loopindex == 1 %}
    <div>
      <a href="{{ post.url }}">{{ post.title }}</a>
  {% else %}
      <a href="{{ post.url }}">{{ post.title }}</a>
    </div>
  {% endif %}
{% endfor %}

This returns your desired output as well, but works for any number of posts.