【问题标题】:Twig loop index into array树枝循环索引到数组中
【发布时间】:2013-07-05 15:06:53
【问题描述】:

我想用 cmets 数组的键 {{loop.index}} 将字符串值显示到数组“nameComments”中,但 {{ nameComments[{{ loop.index }}] }} 显示错误

{% for com in comments %}
    <p>Comment {{ nameComments[{{ loop.index }}] }} : "{{ com['comment'] }}"</p>
{% endfor %}

如果我尝试:

{% for com in comments %}
    <p>Comment {{ nameComments[1] }} : "{{ com['comment'] }}"</p>
{% endfor %}

{{ loop.index }} 向我展示价值:1

那么如何在我的数组中实现循环索引?

【问题讨论】:

    标签: arrays loops for-loop indexing twig


    【解决方案1】:
    {% for com in comments %}
        <p>Comment {{ nameComments[ loop.index ] }} : "{{ com['comment'] }}"</p>
    {% endfor %}
    

    只需省略大括号即可。这应该可以正常工作。 顺便说一句,loop.index 是 1 索引。如果你遍历一个通常以索引 0 开头的数组,你应该考虑使用loop.index0

    documentation

    【讨论】:

    • 很高兴注意到loop.index0。当您忘记这一点时,这会让您发疯! ;-)
    【解决方案2】:

    如果数组索引不是从 1 或 0 开始或不遵循序列,或者它们不是整数,则迭代数组索引的实际值而不使用 loop.index 和 loop.index0 会更安全.

    为此,请尝试以下操作:

    {% for key,com in comments %}
        <p>Comment {{ nameComments[key] }} : "{{ com['comment'] }}"</p>
    {% endfor %}
    

    documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 2019-05-11
      相关资源
      最近更新 更多