현재 루프 반복을 템플릿으로 출력하고 싶습니다.
문서에 따르면 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>
내 템플릿에 아무것도 출력되지 않습니다. 올바른 구문은 무엇입니까?
답변
루프 내부의 카운터 변수 를 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/ 를 참조하십시오 .
답변
for-loop 블록 내에서 loop.index
–but no를 포함한 일부 특수 변수에 액세스 할 수 있습니다 loop.counter
. 에서 공식 문서 :
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).
답변
django를 사용 forloop.counter
하는 경우 대신loop.counter
<ul>
{% for user in userlist %}
<li>
{{ user }} {{forloop.counter}}
</li>
{% if forloop.counter == 1 %}
This is the First user
{% endif %}
{% endfor %}
</ul>