【问题标题】:How to loop over sequence with variable in Twig?如何在 Twig 中使用变量循环序列?
【发布时间】:2020-07-16 15:15:52
【问题描述】:

根据Twig's documentation on the "for" tag.. 运算符可用于遍历数字序列:

{% for i in 0..10 %}
    * {{ i }}
{% endfor %}

是否可以使用存储上限的变量而不是硬编码的数字?例如,

{% set max = 10 %}
...
{% for i in 0..{{ max }} %}
    * {{ i }}
{% endfor %}

当我尝试上面的代码时,我得到了这个错误:

哈希键必须是带引号的字符串、数字、名称或括在括号中的表达式(值“{”的意外标记“标点符号”。

【问题讨论】:

    标签: for-loop twig


    【解决方案1】:

    你应该可以像这样使用变量

    {% set max = 10 %}
    ...
    {% for i in 0..max %}
        * {{ i }}
    {% endfor %}
    

    playground example

    【讨论】:

    • 嗯,这很容易。谢谢。我不知道我是怎么错过的!
    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多