我试图在我的Jinja2模板中引用一个特定的字典值,但它似乎只允许我用整数索引而不是命名键引用。
这是我的Flask / Python3.6代码:
data_dict = {"saved_selections": {}, "records": 0}
for row in cursor.fetchall():
data_dict["saved_selections"].update({"question" + row[1]: row[2]})
行中的数据是3列(已确认)。索引1是ID字段,索引2是我想要存储的值。
在我的html模板中,我尝试过:
“data_dict”在函数中返回并存储在名为“data”的变量中,该变量在“render_template”函数中返回。
<option value="Not Reviewed" {% if data[0][0][2]=="Not Reviewed" %} selected="selected"{% endif %}>Not Reviewed</option>
和:
<option value="Not Reviewed" {% if data['saved_selections']['question1'][2]=="Not Reviewed" %} selected="selected"{% endif %}>Not Reviewed</option>
当我尝试命名键方式时,我收到错误:
jinja2.exceptions.UndefinedError:dict对象没有元素'saved_selections'
以下是我的查询中返回的一些示例数据(如果有用):
LatestRound ReviewItemTaskID ReviewItemValue
6 2 Yes
6 3 Yes
6 4
6 5 No - Provided Training
6 6 No - Requested Update
我最终只是试图返回一个字典,其中包含每行的值(在名为“saved_selections”的单个键下),另一个名为“records”的键将存储返回的总行数,然后能够引用它们我的模板,无需迭代for循环。
编辑:认为添加我希望我的数据看起来像是有帮助的:
data_dict = {
"saved_selections": {
"question1": "Yes",
"question2": "Not Reviewed",
"question3": "No - Provided Training"
},
"records": 3
}
编辑2:这是视图函数,其中定义和返回数据:
@app.route("/main", methods=["POST"])
def main_page():
data = (c.getReviewData(location=request.form['location'])
return render_template("main.html", data=data, location=location)
你的data_dict
可能有问题。也许你在某处覆盖它,或者将错误的字典重新调整为jinja。
首先这个
<option value="Not Reviewed" {% if data['saved_selections']=="banana" %} selected="selected"{% endif %}>Not Reviewed</option>
与这个render_template
组合
return render_template('test.html', data={'saved_selections': 'banana'})
确保您的词典是正确的。
但是我们需要看到整个烧瓶路线以便在这里找到问题。