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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…