Home > Software design >  How to set loop.index as a variable in Jinja
How to set loop.index as a variable in Jinja

Time:11-03

{% for data in data_list %}
    {% set data_index = {{loop.index}} %} 
   for data_dict in data:
     pass
            

In my inner loop, I need to use the loop index in the outer loop, so I intend to set it to a variable as above. But the syntax is invalid.

How to do that? Or is there another way to get the outer loop index?

CodePudding user response:

i think, you should not use Expressions({{..}}) inside statements ({%..%}), try this :

{% for data in data_list %}
    {% set data_index = loop.index %} 
   for data_dict in data:
     pass

CodePudding user response:

You could use the built-in enumerate function for the same to get i as the variable and also use it in an inner loop if you want.

{% for i,data in enumerate(data_list) %}
    {{ i }}
    {% for j in range(i) %}
    {% endfor %}
{% endfor }

All you need to do is pass enumerate or whatever built-in python function you need as a parameter to the render template function as shown below

@app.get("/foo")
def foo():
    return render_template("foo.html", enumerate=enumerate, range=range)
  • Related