Search code examples
twigphp-7.2symfony5

Twig If statement within for loop opening tag


I have this code that is supposed to count items in a for loop retrieved from an object. This code is running on a symfony 5.0 project with php 7.2.5 and 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 }}

and it gives the following error:

Symfony error message

When I run this same code on Symfony 4.2 using php 7.1.3 and twig-bundle 4.2, everything works without an error.

enter image description here

is there any change to the twig-bundle code syntax that I am not using correctly or what am I missing?


Solution

  • I found a way of achieving this by using filter as recommended by Twitter user: @dbrumann

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