2012-08-27 2 views
77

현재 루프 반복을 내 템플리트에 출력 할 수 있기를 원합니다.python jinja template에서 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

'{% userlist %}의 사용자 %'가 두 번 있습니다. 나는 그것이 옳지 않다고 생각한다. – obmarg

답변

176

루프 내의 카운터 변수는 loop.index이고 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 

그 이상을 http://jinja.pocoo.org/docs/templates/를 참조하십시오.

+68

0 기반 색인을 원한다면 대신 "loop.index0'을 사용할 수 있습니다. – ereOn

+0

완전히 놀랍습니다. 카운터와 카운터 0은 문서화되었지만 어제 설치 한 버전에는없는 반면, 나는이 웹 사이트에서 찾을 수 없었습니다. – 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

이 링크가 질문에 대답 할 수 있지만 여기에 답의 핵심 부분을 포함하고 참조 용 링크를 제공하는 것이 좋습니다. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. - [From Review] (리뷰/저품절 게시물/18242231) – Isma

0

또한 루프 구조 위에 태그를 붙여 카운터를 가져올 수 있습니다.

<ol> 
    {% for i in users %} 
     <li>ITEM</li> 
    {% endfor%} 
    </ol> 
관련 문제