在django的模板中,有forloop這一模板變量,頗似php Smarty中的foreach.customers,
Smarty foreach如下:
{foreach name=customers from=$custid item=curr_id}
{$smarty.foreach.customers.iteration} <-- Tells you which item you are at (integer)
{$smarty.foreach.customers.first} <-- Tells you if the current item is the first item (boolean)
{$smarty.foreach.customers.last} <-- Tells you if the current item is the last item (boolean)
{$smarty.foreach.customers.total} <-- Tells you how many items are in the array (integer)
{/foreach}
而django forloop如下:
在每個`` {% for %}``循環里有一個稱為`` forloop`` 的模板變量。這個變量有一些提示循環進度信息的屬性。
forloop.counter 總是一個表示當前循環的執行次數的整數計數器。 這個計數器是從1開始的,所以在第一次循環時 forloop.counter 將會被設置為1。
{% for item in todo_list %}
<p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}
forloop.counter0 類似於 forloop.counter ,但是它是從0計數的。 第一次執行循環時這個變量會被設置為0。
forloop.revcounter 是表示循環中剩余項的整型變量。 在循環初次執行時 forloop.revcounter 將被設置為序列中項的總數。 最后一次循環執行中,這個變量將被置1。
forloop.revcounter0 類似於 forloop.revcounter ,但它以0做為結束索引。在第一次執行循環時,該變量會被置為序列的項的個數減1。
forloop.first 是一個布爾值,如果該迭代是第一次執行,那么它被置為```` 在下面的情形中這個變量是很有用的:
System Message: WARNING/2 (<string>, line 1071); backlink
Inline literal start-string without end-string.
{% for object in objects %}
{% if forloop.first %}<li class="first">{% else %}<li>{% endif %}
{{ object }}
</li>
{% endfor %}
forloop.last 是一個布爾值;在最后一次執行循環時被置為True。 一個常見的用法是在一系列的鏈接之間放置管道符(|)
{% for link in links %}{{ link }}{% if not forloop.last %} | {% endif %}{% endfor %}
上面的模板可能會產生如下的結果:
Link1 | Link2 | Link3 | Link4
另一個常見的用途是為列表的每個單詞的加上逗號。
Favorite places:
{% for p in places %}{{ p }}{% if not forloop.last %}, {% endif %}{% endfor %}
forloop.parentloop 是一個指向當前循環的上一級循環的 forloop 對象的引用(在嵌套循環的情況下)。 例子在此:
{% for country in countries %}
<table>
{% for city in country.city_list %}
<tr>
<td>Country #{{ forloop.parentloop.counter }}</td>
<td>City #{{ forloop.counter }}</td>
<td>{{ city }}</td>
</tr>
{% endfor %}
</table>
{% endfor %}
forloop 變量僅僅能夠在循環中使用。 在模板解析器碰到{% endfor %}標簽后,forloop就不可訪問了。
Context和forloop變量
在一個 {% for %} 塊中,已存在的變量會被移除,以避免 forloop 變量被覆蓋。 Django會把這個變量移動到 forloop.parentloop 中。通常我們不用擔心這個問題,但是一旦我們在模板中定義了 forloop 這個變量(當然我們反對這樣做),在 {% for %} 塊中它會在 forloop.parentloop 被重新命名。