如何在Jinja2模板中不迭代地引用字典值?

时间:2018-09-15 19:38:11

标签: python flask jinja2

我正在尝试在我的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”在函数中返回并存储在名为   在“ 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)

1 个答案:

答案 0 :(得分:0)

您的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'})

为确保您的字典正确无误。

但是我们需要查看整个烧瓶路径,以便在此处找到问题。