用于Twig或Swig的循环计数器

时间:2012-08-24 03:22:41

标签: node.js twig

任何人都知道在Twig / Swig中做到这一点的干净方法:

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

3 个答案:

答案 0 :(得分:15)

如果您有一个数字,那么您可以将其转换为数组,然后使用Swig标准作为标记。这是最简单的,如果你总是想要开始&#39;从0开始的循环。

例如:

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

{# This will run productCount times #}
{% for x, y in productCountAsArray %}
    This is for number: {{ x }}
{% endfor %}

答案 1 :(得分:8)

swig文档已经(ivoba的答案)已更新,现在包含special loop variables,其中包括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

答案 2 :(得分:1)

对于树枝:

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

来自http://twig.sensiolabs.org/doc/tags/for.html

对于swig,文档还没有提到它: https://github.com/paularmstrong/swig/blob/master/docs/tags.md#for

我真的不能说但是它可能不会受到支持,因为它的django受到启发而django似乎也缺乏这个功能:https://code.djangoproject.com/ticket/5172

所以我想将swig部分传递给下一部分。