Symfony 细枝模板-循环中的循环迭代和项

Symfony 细枝模板-循环中的循环迭代和项,symfony,templates,for-loop,twig,iteration,Symfony,Templates,For Loop,Twig,Iteration,我需要将totalPrice值添加到循环中的自身,以计算出循环中项目的总价 这可能吗?Twig中的变量具有作用域,因此首先需要在循环之前设置变量: {% for product in products %} {% set totalPrice = (product.quantity * product.price)|number_format(2, '.', ',') %} {% endfor %} {{ totalPrice }} 然后在循环内求和: {% set totalPr

我需要将
totalPrice
值添加到循环中的自身,以计算出循环中项目的总价


这可能吗?

Twig中的变量具有作用域,因此首先需要在循环之前设置变量

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

{{ totalPrice }}
然后在循环内求和:

{% set totalPrice = 0 %}
并以适当的格式打印和:

{% for product in products %}

    {% set totalPrice = totalPrice + (product.quantity * product.price) %}

{% endfor %}

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