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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With