【问题标题】:Shopify: how to get value of forloop.index outside of the loop?Shopify:如何在循环外获取 forloop.index 的值?
【发布时间】:2014-11-28 22:01:30
【问题描述】:

当我尝试将 forloop 索引(或其他任何内容)分配给 for 循环中的变量,然后在循环外部(之后)使用它时,分配的值会丢失。下面的代码是我尝试过的大约 20 种不同方法之一。他们都没有工作。我只需要知道 x 是否包含 y(因此变量可以是布尔值或整数或任何值)。

{% assign has_y = 0 %}
{% for x in collection %} 
  {% if x contains y %}
    <span style="display: none">{{ has_y | plus: 1 }}</span>
  {% endif %}
{% endfor %}
{% if has_y < 1 %}
   THIS DOESN'T WORK AS EXPECTED
{% endif %}

我对 Shopify 的范围规则感到困惑...

【问题讨论】:

    标签: for-loop scope shopify liquid


    【解决方案1】:

    问题是您正在输出 {{ has_y | plus: 1 }},但没有在 for 循环内为 has_y 分配任何内容。

    试试这个:

    {% assign has_y = 0 %}
    
    {% for x in collections %} 
      {% if x contains y %}
        {% assign has_y = has_y | plus: 1 %}
        <span style="display: none">{{ has_y }}</span>
      {% endif %}
    {% endfor %}
    
    {% if has_y < 1 %}
       ...
    {% endif %}
    

    或者,如果您想改用布尔值:

    {% assign has_y = false %}
    
    {% for x in collections %} 
      {% if x contains y %}
        {% assign has_y = true %}
        <span style="display: none">{{ has_y }}</span>
      {% endif %}
    {% endfor %}
    
    {% if has_y == false %}
      ...
    {% endif %}
    

    另外,您可能需要检查您的 for 循环 {% for x in collection %}collection 是一个对象。也许您的意思是迭代 collection.productscollections

    【讨论】:

    • 谢谢。我看到我不明白作业或数学过滤器是如何工作的。 (我确实知道迭代集合。我只是简化了那部分以减少粘贴代码中的混乱。)再次感谢!
    • @MountainX 没问题 :)
    猜你喜欢
    • 2015-12-26
    • 2017-08-03
    • 2016-11-30
    • 2020-05-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多