Andrew Heekin
Andrew Heekin

Reputation: 671

Jinja2/Flask dynamic variable name change

I have a Flask method and index.html snippet with a jinja2 for loop

def recommendations():
    return render_template("index.html", score1='46', score2='12', score3='15', score4='33')

index.html:

{% for i in range(1,5) %}
   <p> Your score: {{ score1 }}</p>
{% endfor %} 

How do I dynamically change the names of the score variable based on the loop like:

<p> Your score: {{ score1 }}</p>
<p> Your score: {{ score2 }}</p>
<p> Your score: {{ score3 }}</p>
<p> Your score: {{ score4 }}</p>

Upvotes: 5

Views: 7411

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121972

You can't create dynamic variables in Jinja2. You should instead use a list:

return render_template("index.html", scores=['46', '12', '15', '33'])

or a dictionary:

return render_template("index.html", scores={
    'score1': '46', 'score2': '12', 'score3': '15', 'score4': '33'})

and adjust your Jinja2 loop accordingly to handle that instead. For the list that's as simple as:

{% for score in scores %}
   <p> Your score: {{ score }}</p>
{% endfor %} 

For the dictionary case you could use sorting to set a specific order:

{% for score_name, score in scores|dictsort %}
   <p> Your score: {{ score }}</p>
{% endfor %} 

and you could use score_name to display the key as well.

Upvotes: 8

Related Questions