精简版:
我想在液体模板中将数字加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>
Run Code Online (Sandbox Code Playgroud)
结果:
-Value of plus_one: 1
-This works: The Zone
-This doesn't:
Run Code Online (Sandbox Code Playgroud)
长版:
我正在使用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>
Run Code Online (Sandbox Code Playgroud)
结果:
<div>value of plus_one: 1</div>
<div>This doesn't work: </div>
<div>This does: A Blog Post Title</div>
Run Code Online (Sandbox Code Playgroud)
我想我的变量'plus_one'的值被视为字符串而不是数字.
有没有办法将其转换为数字?
还是有另一种方法来实现我想要做的事情?
小智 9
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
正如您所提到的,您可以保存并使用上一个帖子链接的前一个迭代值(在我的情况下,我将其用作下一个帖子链接,因为我不想要默认的最新 - 第一个顺序).对于您可以使用的下一个数组元素forloop.index.这是for循环的从1开始的索引,它将为您提供从零开始的数组的下一项.
assign 保留数字:
{% for item in items %}
{% assign next_i = forloop.index0 | plus: 1 %}
{% assign prev_i = forloop.index0 | minus: 1 %}
{{ items[next_i] }}
{{ items[prev_i] }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6281 次 |
| 最近记录: |