我知道我来晚了,但我找到了一个相当优雅的解决方案,感觉不像是hacky。
通过for
循环的limit
和offset
参数,我们可以每次迭代一行,每行N个帖子。
首先,我们计算需要枚举的行数:
{% assign rows = site.posts.size | divided_by: 2.0 | ceil %}
在 Ruby 中等价的代码为 rows = (posts.size / 2.0).ceil
(奇数会分到自己的一行)。
接下来,我们将遍历这些行:
{% for i in (1..rows) %}
<div>
现在我们需要使用 forloop.index0
计算集合的偏移量:(i - 1) * 2
:
{% assign offset = forloop.index0 | times: 2 %}
然后,我们可以迭代遍历帖子片段,该片段从行偏移开始(相当于 Ruby 中的 posts[offset, 2]
):
{% for post in site.posts limit:2 offset:offset %}
<a href="{{ post.url }}">{{ post.title }}</a>
{% endfor %}
关闭行的 div
元素并结束循环:
</div>
{% endfor %}
就是这样了!
在 Ruby 中,这将是:
rows = (posts.size / 2.0).ceil
(1..rows).each do |i|
offset = (i - 1) * 2
posts[offset, 2].each do |post|
end
end
现在,全部在 Liquid 中:
{% assign rows = site.posts.size | divided_by: 2.0 | ceil %}
{% for i in (1..rows) %}
{% assign offset = forloop.index0 | times: 2 %}
<div>
{% for post in site.posts limit:2 offset:offset %}
<a href="{{ post.url }}">{{ post.title }}</a>
{% endfor %}
</div>
{% endfor %}
希望这能帮到某些人!