2

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?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Eddy
  • 139
  • 1
  • 14

3 Answers3

3

Try this :

{% set sent_mails = 0 %}

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

{{ sent_mails }}
Mickaël Leger
  • 3,426
  • 2
  • 17
  • 36
  • yes, this will work but is this a clean and efficient way of doing it? – Eddy Dec 03 '19 at 09:58
  • What's not efficient ? You have a loop and a condition to know how many mail you sent, what's wrong ? Here is an other question that looks like yours : https://stackoverflow.com/questions/41702618/filtering-and-splicing-an-array-in-twig – Mickaël Leger Dec 03 '19 at 10:01
3

Using an if inside a for is deprecated:

Using an "if" condition on "for" tag in "main.twig" at line 1 is deprecated since Twig 2.10.0, use a "filter" filter or an "if" condition inside the "for" body instead (if your condition depends on a variable updated inside the loop).

source

DarkBee
  • 16,592
  • 6
  • 46
  • 58
2

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 }}
Eddy
  • 139
  • 1
  • 14