2015-02-05 73 views
1

我有一個瓶法並用的Jinja2 index.html的內容片段在循環的Jinja2 /瓶動態變量名稱變更

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 %} 

如何動態地更改名稱基於循環的得分變量:

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

我已經嘗試{%爲我在範圍內(1,5)%}

您的評分​​:{{分數+ i}}

{%endfor%} – 2015-02-05 17:11:56

回答

2

您不能在Jinja2中創建動態變量。你應該使用一個列表:

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

或字典:

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

,並相應地調整你的Jinja2的循環來處理吧。對於這一樣簡單列表:

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

對於您可以使用排序來設置特定的順序字典情況:

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

,你可以使用顯示鍵也是如此。

+0

謝謝先生! – 2015-02-05 18:44:48