sort last jinja for comment python jinja2

python - last - jinja2 comment line



¿Cómo sacar loop.counter en la plantilla python jinja? (3)

Además, puede colocar la etiqueta sobre la estructura del bucle y obtendrá su contador.

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

Quiero poder dar salida a la iteración del ciclo actual a mi plantilla.

De acuerdo con los documentos: http://wsgiarea.pocoo.org/jinja/docs/loops.html , hay una variable loop.counter que estoy tratando de usar.

Tengo lo siguiente:

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

Aunque no se está produciendo nada en mi plantilla. ¿Cual es la sintaxis correcta?


Dentro de un bloque for-loop, puede acceder a algunas variables especiales, incluido loop.index --pero no loop.counter . De los documentos oficiales :

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).


La variable del contador dentro del ciclo se llama loop.index en 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

Ver http://jinja.pocoo.org/docs/templates/ para más.