Jinja2/Flask 动态变量名更改

And*_*kin 4 jinja2 flask

我有一个带有 jinja2 for 循环的 Flask 方法和 index.html 片段

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

索引.html:

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

如何根据循环动态更改分数变量的名称,例如:

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

Mar*_*ers 7

你不能在 Jinja2 中创建动态变量。您应该改为使用列表:

return render_template("index.html", scores=['46', '12', '15', '33'])
Run Code Online (Sandbox Code Playgroud)

或字典:

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

并相应地调整您的 Jinja2 循环来处理它。对于简单的列表:

{% for score in scores %}
   <p> Your score: {{ score }}</p>
{% endfor %} 
Run Code Online (Sandbox Code Playgroud)

对于字典情况,您可以使用排序来设置特定顺序:

{% for score_name, score in scores|dictsort %}
   <p> Your score: {{ score }}</p>
{% endfor %} 
Run Code Online (Sandbox Code Playgroud)

你也可以score_name用来显示密钥。