Zac*_*101 4 iteration templates for-loop symfony twig
{% for product in products %}
{% set totalPrice = (product.quantity * product.price)|number_format(2, '.', ',') %}
{% endfor %}
{{ totalPrice }}
Run Code Online (Sandbox Code Playgroud)
我需要totalPrice在循环内将值添加到自身,以得出循环内物品的总价。
这可能吗?
Twig 中的变量有作用域,因此首先你需要在 循环之前设置变量:
{% set totalPrice = 0 %}
Run Code Online (Sandbox Code Playgroud)
然后在循环内求和:
{% for product in products %}
{% set totalPrice = totalPrice + (product.quantity * product.price) %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
并在 和 以正确格式打印总和:
{{ totalPrice|number_format(2, '.', ',') }}
Run Code Online (Sandbox Code Playgroud)