2012-08-24 153 views
6

任何人都知道的一個乾淨的方式循環計數器爲此在枝杈/痛飲:用枝條或痛飲

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

(http://twig.sensiolabs.org/doc/tags/for.html) – moonwave99

+0

說實話,我認爲痛飲成爲一個完整的樹枝端口 - 顯然不是。我正在使用Swig,只查看這些文檔。 – cyberwombat

回答

1

對於枝杈其:

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

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

對於痛飲文檔中沒有提及它: https://github.com/paularmstrong/swig/blob/master/docs/tags.md#for

ic螞蟻真的說,但它可能不支持在swig,因爲它的django的啓發和django似乎也缺乏這種功能nativly:https://code.djangoproject.com/ticket/5172

所以我想通過swig部分到下一個。

+0

看來swig不支持這個功能。我將標記爲答案,因爲它適用於Twig。謝謝 – cyberwombat

8

的痛飲文檔具有自(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

14

如果你有一個數字,然後你可以將它轉換爲一個數組,然後使用Swig的標記標記。如果你總是想從0開始循環,這是最簡單的。

例如:[?難道你不相信樹枝文檔]

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

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

很好的答案。爲我工作,我只有一個問題。爲什麼在for循環中使用兩個變量,即'x'和'y'?是否因爲'x'作爲數組計數器而'y'存儲數組的內容? – Daggerhunt

+1

謝謝,我在SWIG中使用了這個。 我的OCD踢了進來,我修剪它到以下: ''{%我在陣列(30)%}等等.... {%endfor%}''' – ConorLuddy