Twig 3:如何使用循环变量迁移 "for item in items if item.foo == 'bar'"
Twig3: How to migrate "for item in items if item.foo == 'bar'" with loop bariable
我使用以下 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 %}
在 twig 文档中:https://twig.symfony.com/doc/2.x/deprecated.html
Adding an if condition on a for tag is deprecated in Twig 2.10. Use a filter
filter or an "if" condition inside the "for" body instead (if your condition depends on a variable updated inside the loop)
我想知道如何将我的 Twig 2 代码迁移到 Twig 3。如您所见,我在 for 循环中使用了循环变量和 else
。我知道我可以使用一个新参数并自己增加它……但这真的是我的意图吗?如何使用 filter
?
重写此代码
你有两种选择来解决这个问题
- 将
if
标签放在循环中
{% 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
变量上 "rely",因为无论是否满足条件,计数器都会继续上升
- 使用
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 %}
使用 filter
过滤器,您的代码将如下所示(另请参阅 https://twigfiddle.com/9hiayc and https://twigfiddle.com/9hiayc/2):
{% for item in items|filter(i => i.foo == 'bar') %}
<span class="{% if loop.index % 2 %}special-class{% endif %}">
{{ item.value }}
</span>
{% else %}
Nothing found
{% endfor %}
我使用以下 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 %}
在 twig 文档中:https://twig.symfony.com/doc/2.x/deprecated.html
Adding an if condition on a for tag is deprecated in Twig 2.10. Use a
filter
filter or an "if" condition inside the "for" body instead (if your condition depends on a variable updated inside the loop)
我想知道如何将我的 Twig 2 代码迁移到 Twig 3。如您所见,我在 for 循环中使用了循环变量和 else
。我知道我可以使用一个新参数并自己增加它……但这真的是我的意图吗?如何使用 filter
?
你有两种选择来解决这个问题
- 将
if
标签放在循环中
{% 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
变量上 "rely",因为无论是否满足条件,计数器都会继续上升
- 使用
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 %}
使用 filter
过滤器,您的代码将如下所示(另请参阅 https://twigfiddle.com/9hiayc and https://twigfiddle.com/9hiayc/2):
{% for item in items|filter(i => i.foo == 'bar') %}
<span class="{% if loop.index % 2 %}special-class{% endif %}">
{{ item.value }}
</span>
{% else %}
Nothing found
{% endfor %}