I want to calculate total numbers for a specific field in Twig
in Php Template, I can easily make it like so
<?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) ?>
How to do it in Twig?
I tried
{% set tl = 0 %}
{% for task in tasks %}
{% set tl += {{ task.amount }} %}
{% endfor %}
{{ tl }}
It doesn't work Any Ideas?
If you are using Twig in another project, you can set your globals directly in the environment: $twig = new Twig_Environment($loader); $twig->addGlobal('myStuff', $someVariable); And then use {{ myStuff }} anywhere in your application.
Looks like twig doesn't support combined operators as PHP do. (I could not find an example in http://twig.sensiolabs.org/doc/templates.html#setting-variables)
Maybe this is relevant: how make addition from 2 variable twig?
Could you try a separate operator version?
{% set tl = tl + task.amount %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With