【问题标题】:How to increment the counter inside a Liquid for loop?如何在 Liquid for 循环中增加计数器?
【发布时间】:2018-06-11 07:11:44
【问题描述】:

我正在努力弄清楚如何在 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】:

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

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

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

    {% assign i = 0 %}
    {% for thing in things %}
        {% assign i = i | plus:1 %}
    {% endfor %}
    

    【讨论】:

      【解决方案2】:

      随便用

      {% increment my_counter %}
      

      创建一个新的数字变量,并在每次调用时将其值加一。初始值为 0。也适用于减量。但是,如果您只有一个简单的计数器,则无法重置并且始终从“0”开始

      【讨论】:

        猜你喜欢
        • 2017-05-26
        • 2013-12-16
        • 2023-03-08
        • 2012-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-06
        • 1970-01-01
        相关资源
        最近更新 更多