Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop counter with Twig or Swig

Tags:

node.js

twig

Anyone know of a clean way to do this in Twig/Swig:

{% for(i = 0; i < 100; i++) %}
    blah....
{% endfor %}
like image 251
cyberwombat Avatar asked Aug 24 '12 03:08

cyberwombat


2 Answers

If you have a number, then you can just convert this to an array and then use Swig's standard for tag. This is simplest if you always want to 'start' the loop from 0 though.

For example:

{% set productCount = 6 %}
{% set productCountAsArray = Array(productCount) %}

{# This will run productCount times #}
{% for x, y in productCountAsArray %}
    This is for number: {{ x }}
{% endfor %}
like image 97
Ben Barnett Avatar answered Sep 25 '22 15:09

Ben Barnett


The swig docs have since (ivoba's answer) been updated and now contain special loop variables, which include loop.index:

{% for x in y %}
  {% if loop.first %}<ul>{% endif %}
  <li>{{ loop.index }} - {{ loop.key }}: {{ x }}</li>
  {% if loop.last %}</ul>{% endif %}
{% endfor %}

http://paularmstrong.github.io/swig/docs/#tags-for

like image 35
antforce Avatar answered Sep 25 '22 15:09

antforce