基本上,我使用
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 %}
原文地址:https://www.jb51.cc/css/218072.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。