如何在循环中用树枝求和值?

How can I sum values with twig in loop?

  {% set totalPrice = 0 %}
  {% for category, product in table %}
    {% for key, value in product|last %}
         {{ value }}
    {% endfor %}
  {% endfor %}

输出为:

60
2

我现在尝试一起计算这些值:

   {% set totalPrice = 0 %}
      {% for category, product in table %}
        {% for key, value in product|last %}
             {{ value }}
             {% set totalPrice = value %}
        {% endfor %}
      {% endfor %}
      Total:    {{ totalPrice }}

我期望的结果是:

60
2
Total: 62

但是我得到的结果是:

60
2
Total: 2

您覆盖了 totalPrice 的值,而不是添加它。所以:使用 set totalPrice = totalPrice + value.

{% set totalPrice = 0 %}
{% for category, product in table %}
  {% for key, value in product|last %}
    {{ value }}
    {% set totalPrice = totalPrice + value %}
  {% endfor %}
{% endfor %}
Total: {{ totalPrice }}