Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2/Flask dynamic variable name change

Tags:

flask

jinja2

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>
like image 545
Andrew Heekin Avatar asked Mar 17 '23 03:03

Andrew Heekin


1 Answers

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.

like image 162
Martijn Pieters Avatar answered Apr 26 '23 09:04

Martijn Pieters