首页 > 解决方案 > Twig3:如何使用循环 bariable 迁移“for item in items if item.foo == 'bar'”

问题描述

我使用以下 Twig 2 代码:

{% for item in items if item.foo == 'bar' %}
   <span class="{% if loop.index % 2 %}special-class{% endif %}">
       {{ item.value }}
   </span>
{% else %}
    Nothing found
{% endfor %}

在树枝文档中:https ://twig.symfony.com/doc/2.x/deprecated.html

在 Twig 2.10 中不推荐在 for 标记上添加 if 条件。在“for”正文中使用filter过滤器或“if”条件(如果您的条件取决于循环内更新的变量)

我想知道如何将我的 Twig 2 代码迁移到 Twig 3。如您所见,我使用循环变量并else在 for 循环中。我知道我可以使用一个新参数并自己增加它......但这真的是意图吗?如何使用 重写此代码filter

标签: symfonytwig

解决方案


你有两个选择来解决这个问题

  1. if-tag 放在循环内
{% set i = 0 %}
{% for item in items %}
    {% if item.foo == 'foo' %}
        <span class="{% if i % 2 %}special-class{% endif %}">
            {{ item.value }}
        </span>
        {% set i = i + 1 %}
    {% endif %}
{% else %}
    Nothing found
{% endfor %}

使用此解决方案,您不能“依赖”内部loop变量,因为无论是否满足条件,计数器都会持续上升

  1. 使用filter- 过滤器
{% for item in items | filter(item => item.foo == 'foo') %}
   <span class="{% if loop.index % 2 %}special-class{% endif %}">
       {{ item.value }}
   </span>
{% else %}
    Nothing found
{% endfor %}

更新的演示


推荐阅读