Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment value in twig file

Tags:

twig

I have a loop withing a .twig file that outputs elements.

I need to increment a value withing each element. I know how to do it in PHP, but an not clear how to do it withing a twig document. I can't really do it in controller. Any suggestions?

{% set myVal = 50 %}  {% for item in items%}      {{ myVal = myVal + 10 }} {% endfor %} 
like image 704
santa Avatar asked Jul 24 '14 20:07

santa


2 Answers

Use this:

{% set myVal = 50 %}  {% for item in items %}      {% set myVal = myVal + 10 %} {% endfor %} 

For declaring, setting values, setting blocks/forms, etc. you must use {% %}. For output, there is {{ }}

like image 88
Lkopo Avatar answered Oct 06 '22 05:10

Lkopo


Here is the better way -

{% for item in items %}   {% set counter = ( counter | default(0) ) + 1 %}   <p>{{ counter ~ ' ). ' ~ item.title }}</p> {% endfor %} 

See how the counter is being increased by 1.

like image 34
RN Kushwaha Avatar answered Oct 06 '22 05:10

RN Kushwaha