Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig Assignment operator

Tags:

php

twig

symfony

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?

like image 783
Danielle Rose Mabunga Avatar asked Jan 21 '16 07:01

Danielle Rose Mabunga


People also ask

How do you set a global variable in Twig?

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.


1 Answers

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 %}
like image 56
Motoroller Avatar answered Sep 26 '22 12:09

Motoroller