Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

jekyll - For loop, wrap every two posts in a div

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...