精简版:
我想将 1 添加到液体模板中的数字并将结果用作数组索引。
{% capture plus_one %}{{ 0 | plus: 1 }}{% endcapture %}
<div>-Value of plus_one: {{plus_one}}</div>
<div>-This works: {{site.posts[1].title}}</div>
<div>-This doesn't: {{site.posts[plus_one].title}}</div>
结果:
-Value of plus_one: 1
-This works: The Zone
-This doesn't:
长版:
我正在使用 Jekyll,没有插件。我想为当前帖子提供指向同一类别下一个帖子的链接。 (在此代码中,类别被硬编码为“journal”。)
我的代码遍历类别数组中的所有帖子,查找当前帖子。找到后,我尝试抓取类别数组中的下一篇文章。
{% for num in (0..site.categories.journal.size) %}
{% assign page2 = site.categories.journal[num] %}
{% if page2.title == page.title and page2.date == page.date %}
{% capture plus_one %}{{ num | plus: 1 }}{% endcapture %}
{% endif %}
{% endfor %}
<div>value of plus_one: {{plus_one}}</div>
<div>This doesn't work: {{site.categories.journal[plus_one].title}}</div>
<div>This does: {{site.categories.journal[1].title}}</div>
结果:
<div>value of plus_one: 1</div>
<div>This doesn't work: </div>
<div>This does: A Blog Post Title</div>
我猜我的变量 'plus_one' 的值被视为字符串而不是数字。
有没有办法将其转换为数字?
或者有另一种方法来实现我想要做的事情吗?
最佳答案
{% for category in site.categories %}
{% assign catg_name = category.first %}
{% if catg_name == page.category %}
{% assign catg_posts = category.last %}
{% endif %}
{% endfor %}
{% for post in catg_posts %}
{% if post.title == page.title %}
{% unless forloop.last %}
{% assign next = catg_posts[forloop.index] %}
<li class="previous">
<a href="{{ site.baseurl }}{{ next.url }}">←{{ next.title }}</a>
</li>
{% endunless %}
{% unless forloop.first %}
<li class="next">
<a href="{{ site.baseurl }}{{ prev.url }}">{{ prev.title }}→</a>
</li>
{% endunless %}
{% endif %}
{% assign prev = post %}
{% endfor %}
正如您所提到的,您可以保存并使用上一个帖子链接的上一个迭代值(在我的情况下,我将它用作下一个帖子链接,因为我不想要默认的最新优先顺序)。对于下一个数组元素,您可以使用
forloop.index
.这是 for 循环的从 1 开始的索引,它将为您提供从零开始的数组的下一项。
关于jekyll - 从液体数组中获取下一个和上一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16145061/