2012-08-27 37 views
77

我想能夠輸出當前循環迭代到我的模板。如何在python jinja模板中輸出loop.counter?

根據文檔:http://wsgiarea.pocoo.org/jinja/docs/loops.html,有一個loop.counter變量,我試圖使用。

我有以下幾點:

<ul> 
{% for user in userlist %} 
    <li> 
     {{ user }} {{loop.counter}} 
    </li> 
     {% if loop.counter == 1 %} 
      This is the First user 
     {% endif %} 
{% endfor %} 
</ul> 

雖然沒有什麼是被輸出到我的模板。什麼是正確的語法?

+0

你有兩次{%user%user}用戶。我認爲這是不對的。 – obmarg

回答

176

循環中的計數器變量在jinja2中被稱爲loop.index

>>> from jinja2 import Template 

>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}" 
>>> Template(s).render(elements=["a", "b", "c", "d"]) 
1 2 3 4 

請參閱http://jinja.pocoo.org/docs/templates/瞭解更多信息。

+68

值得一提的是,如果你想要一個基於0的索引,你可以使用''loop.index0''代替。 – ereOn

+0

什麼是令人驚訝的是,這個我在他們的網站上找不到的引用,而counter和counter0被記錄在案,但沒有出現在我昨天安裝的版本中。 – njzk2

6

在for循環塊中,您可以訪問一些特殊變量,包括loop.index - 但沒有loop.counter。從the official docs

Variable Description 
loop.index The current iteration of the loop. (1 indexed) 
loop.index0 The current iteration of the loop. (0 indexed) 
loop.revindex The number of iterations from the end of the loop (1 indexed) 
loop.revindex0 The number of iterations from the end of the loop (0 indexed) 
loop.first True if first iteration. 
loop.last True if last iteration. 
loop.length The number of items in the sequence. 
loop.cycle A helper function to cycle between a list of sequences. See the explanation below. 
loop.depth Indicates how deep in a recursive loop the rendering currently is. Starts at level 1 
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0 
loop.previtem The item from the previous iteration of the loop. Undefined during the first iteration. 
loop.nextitem The item from the following iteration of the loop. Undefined during the last iteration. 
loop.changed(*val) True if previously called with a different value (or not called at all). 
+0

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/18242231) – Isma

0

此外,您還可以把標籤上的循環結構,你會得到你的櫃檯。

<ol> 
    {% for i in users %} 
     <li>ITEM</li> 
    {% endfor%} 
    </ol>