for loop counter with Twig or Swig

2019-04-28 23:29发布

问题:

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

{% for(i = 0; i < 100; i++) %}
    blah....
{% endfor %}

回答1:

For twig its:

{% for i in 0..100 %}
    * {{ i }}
{% endfor %}

From http://twig.sensiolabs.org/doc/tags/for.html

For swig the docs dont mention it yet: https://github.com/paularmstrong/swig/blob/master/docs/tags.md#for

i cant really tell but it might be not supported in swig since its django inspired and django also seems to lack this feature nativly: https://code.djangoproject.com/ticket/5172

so i would like to pass the swig part to the next one.



回答2:

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 %}


回答3:

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



标签: node.js twig