2

我有这段代码应该计算从对象中检索到的 for 循环中的项目。此代码在 symfony 5.0 项目上运行,带有 php 7.2.5 和 twig-bundle 5.0

{% set sent_mails = 0 %}

 {% for email in emails if email.status == 1 %}
    {% set sent_mails = (sent_mails + 1) %}
 {% endfor %}

{{ sent_mails }}

它给出了以下错误:

Symfony 错误信息

当我使用 php 7.1.3 和 twig-bundle 4.2 在 Symfony 4.2 上运行相同的代码时,一切正常,没有错误。

在此处输入图像描述

我没有正确使用的 twig-bundle 代码语法是否有任何更改或我缺少什么?

4

3 回答 3

3

不推荐使用if内部 a for

自 Twig 2.10.0 以来,不推荐在第 1 行的“main.twig”中的“for”标签上使用“if”条件,而是在“for”正文中使用“filter”过滤器或“if”条件(如果您条件取决于循环内更新的变量)。

资源

于 2019-12-03T10:05:03.757 回答
2

尝试这个 :

{% set sent_mails = 0 %}

{% for email in emails %}
    {% if email.status == 1 %}
        {% set sent_mails = (sent_mails + 1) %}
    {% endif %}
{% endfor %}

{{ sent_mails }}
于 2019-12-03T09:57:15.700 回答
1

我找到了一种通过使用 Twitter 用户推荐的过滤器来实现此目的的方法:@dbrumann

{% set sent_mails = 0 %}
   {% for email in emails|filter(email => email.status == 1) %}
    {% set sent_mails = (sent_mails + 1) %}
   {% endfor %}

{{ sent_mails }}
于 2019-12-03T10:58:34.650 回答