for loop counter with Twig or Swig

2019-04-28 22:52发布

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

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

标签: node.js twig
3条回答
萌系小妹纸
2楼-- · 2019-04-28 23:41

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

查看更多
beautiful°
3楼-- · 2019-04-28 23:46

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 %}
查看更多
疯言疯语
4楼-- · 2019-04-28 23:50

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.

查看更多
登录 后发表回答