我想计算 Twig 中特定字段的总数
在 PHP 模板中,我可以很容易地做到这样
<?php $tl = 0; ?>
<?php foreach($loo as $l):>
<?php $tl += $l['amount'] ?>
<tr>
<td><?php echo $l['amount'] ?>
</tr>
<?php endforeach ?>
<p><?php echo number_format($tl,2) ?>
Run Code Online (Sandbox Code Playgroud)
如何在 Twig 中做到这一点?
我试过
{% set tl = 0 %}
{% for task in tasks %}
{% set tl += {{ task.amount }} %}
{% endfor %}
{{ tl }}
Run Code Online (Sandbox Code Playgroud)
它不起作用任何想法?
看起来 Twig 不像 PHP 那样支持组合运算符。(我在http://twig.sensiolabs.org/doc/templates.html#setting-variables 中找不到示例)
也许这是相关的: 如何从 2 个可变树枝进行加法?
您可以尝试单独的运营商版本吗?
{% set tl = tl + task.amount %}
Run Code Online (Sandbox Code Playgroud)