Twig template - Loop iteration sum items in loop Twig template - Loop iteration sum items in loop symfony symfony

Twig template - Loop iteration sum items in loop


Variables in Twig have scopes, therefore first you need to set the variable before loop:

{% set totalPrice = 0 %}

Then make the sum inside the loop:

{% for product in products %}    {% set totalPrice = totalPrice + (product.quantity * product.price) %}{% endfor %}

And in the and print the sum in proper format:

{{ totalPrice|number_format(2, '.', ',') }}

Twig's set documentation