如何增加Liquid for循环中的计数器?

问题描述 投票:3回答:1

我正在努力弄清楚如何在Liquid / Jekyll中的for循环中增加索引变量。目前,我有类似的东西

{% for i in (0..num_posts) %}
    {% if i < some_value %}
        do_thing
    {% else %}
    {% endif %}
    {% assign i = i|plus:1 %}
    {% if i<some_value %}
        do_another_thing
    {% else %}
    {% endif %}
{% endfor %}

问题是,它不是递增i,而是将i保留为相同的值。

我尝试过的事情:

  1. 使用{% assign i = i|plus:1 %}
  2. 使用{% increment i %}
  3. 运用 {% assign j = i|plus:1 %} {% assign i = j %}

我不能使用offset命令,因为代码并不总是只检查循环中的2个if语句。

有任何想法吗?

jekyll liquid
1个回答
6
投票

在这里,我不是指数。要获取当前索引,请使用{{forloop.index}}。

{% if forloop.index < 5 %}
    Do something
{% endif %}

要在循环中分配自己的自定义索引,您可以使用以下内容:

{% assign i = 0 %}
{% for thing in things %}
    {% assign i = i | plus:1 %}
{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.