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

2024-09-27 01:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的Jinja2模板中引用一个特定的字典值,但它似乎只允许我引用整数索引而不是命名键。在

这是我的烧瓶/Python3.6代码:

data_dict = {"saved_selections": {}, "records": 0}
for row in cursor.fetchall():
    data_dict["saved_selections"].update({"question" + row[1]: row[2]})

行中的数据为3列(已确认)。Index 1是ID字段,Index 2是我要存储的值。在

在我的html模板中,我尝试过:

"data_dict" is returned in a function and stored in variable called "data" which is returned in the "render_template" function.

^{pr2}$

以及:

<option value="Not Reviewed" {% if data['saved_selections']['question1'][2]=="Not Reviewed" %} selected="selected"{% endif %}>Not Reviewed</option>

当我尝试命名密钥方式时,我得到错误:

jinja2.exceptions.UndefinedError: dict object has no element '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)

Tags: 数据noin模板datamainnotlocation
1条回答
网友
1楼 · 发布于 2024-09-27 01:21:17

您的data_dict可能有问题。也许你在某个地方重写了它,或者把错误的口述告诉了金贾。在

首先是这个

<option value="Not Reviewed" {% if data['saved_selections']=="banana" %} selected="selected"{% endif %}>Not Reviewed</option>

与此render_template结合使用

^{pr2}$

确保你的口述是正确的。在

但我们需要查看整个烧瓶的路线才能找到问题所在。在

相关问题 更多 >

    热门问题