JP101 JP101 - 2 months ago 22
Twig Question

Twig template - Loop iteration sum items in loop

{% for product in products %}
{% set totalPrice = (product.quantity * product.price)|number_format(2, '.', ',') %}
{% endfor %}

{{ totalPrice }}


I need to add the
totalPrice
value to itself within the loop, to out the total price of the items within the loop.

Is this possible?

Answer

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