简体   繁体   English

如何在循环中将值与 twig 相加?

[英]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 %}

The output is: output 是:

60
2

I try now to count the values together:我现在尝试将这些值一起计算:

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

The result I expect is:我期望的结果是:

60
2
Total: 62

But the result I get is:但我得到的结果是:

60
2
Total: 2

You override totalPrice 's value, rather than adding to it.您覆盖totalPrice的值,而不是添加到它。 So: use set totalPrice = totalPrice + value .所以:使用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 }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM