jekyll – For循环,在div中包含每两个帖子

基本上,我使用 Jekyll(使用 Liquid模板语言),我正在尝试写一个for循环,每个div都包含两个项目。

这是我当前的循环:

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

这将输出四个帖子如下:

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

我想要输出四个职位是:

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

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

我该如何做到这一点?

解决方法

如果< div> s和帖子的数量是固定的(根据您选择的答案似乎是这种情况),有一个较短的方法来获得相同的输出 – 使用limit和offset:
(液体的分页方法)
<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>

更好的解决方案:

如果帖子数量不固定(所以当你有100个帖子时,你需要每个50个< div> s两个帖子),那么你可以使用forloop.index(这在大多数其他答案中已经提到),并使用模数,以确定当前索引是偶数还是奇数:

{% 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 %}

这也会返回您所需的输出,但适用于任何数量的帖子。

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效