2012-08-27 15 views
77

Chcę móc wyprowadzić bieżącą iterację pętli do mojego szablonu.Jak wypisać loop.counter w szablonie python jinja?

Według dokumentów: http://wsgiarea.pocoo.org/jinja/docs/loops.html, istnieje zmienna loop.counter, której próbuję użyć.

mam następujące:

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

Choć nic nie jest wyjście do mojego szablonu. Jaka jest prawidłowa składnia?

+0

Masz ''% dla użytkownika w liście użytkowników%} 'dwa razy. Zakładam, że to nie w porządku. – obmarg

Odpowiedz

176

Zmienna licznika w pętli nazywa się loop.index w jinja2.

>>> from jinja2 import Template 

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

Więcej informacji na stronie http://jinja.pocoo.org/docs/templates/.

+68

Warto nadmienić, że jeśli chcesz mieć indeks bazujący na 0, możesz zamiast tego użyć '' loop.index0''. – ereOn

+0

niesamowite jest to, że odniesienie do tego nie mogłem znaleźć na ich stronie internetowej, podczas gdy licznik i counter0 są udokumentowane, ale nie są obecne w wersji zainstalowanej wczoraj. – njzk2

6

Wewnątrz bloku pętli for można uzyskać dostęp do niektórych zmiennych specjalnych, w tym loop.index - ale nie loop.counter. Od 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

Podczas gdy ten link może odpowiedzieć na pytanie, lepiej umieścić tutaj istotne części odpowiedzi i podać link do odsyłacza. Odpowiedzi dotyczące linków mogą stać się nieprawidłowe, jeśli strona z linkami się zmieni. - [Z recenzji] (/ opinia/niskiej jakości-posts/18242231) – Isma

0

Ponadto, można umieścić znacznik nad strukturą pętli, a dostaniesz swój licznik.

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