【发布时间】:2019-02-24 19:06:04
【问题描述】:
Similar question 这并不能解决我的问题。
我有一个 Flask 应用程序,它从数据库中读取数据并使用数据库数据呈现 HTML 模板。在将它发送到 HTML 模板之前,我试图操纵从数据库获得的值,但这不起作用。
Python 代码:
@app.route('/pilot', methods=['GET'])
def form_view():
result = {}
# query DB and get cursor
numQuestions = 0
for row in cursor:
row.pop('_id', None) # delete the key and add modified key back
row['_id'] = row['stage'][-1] # get only last char- eg, "1" from "stage1", "2" from "stage2" and so on
print(row['_id'])
result[numQuestions] = row
numQuestions += 1
return render_template("form.html", count=numQuestions, result=result, debug=app.debug)
在终端上运行时的输出符合预期:
1
1
1
2
2
2
form.html 的 Jinja2 片段:
{% for row in result[row_num]['scrutiny_stage'] %}
{{ row['_id'] }}
{% endfor %}
浏览器输出:
stage1 stage1 stage1 stage2 stage2 stage2 stage2
谁能帮我理解我在这里做错了什么以及如何获得我在 Python 代码中设置的变量的正确值以显示在 Flask 呈现的 HTML 模板中?
谢谢。
【问题讨论】:
-
此代码无法给出该结果。您传递给模板的
result对象没有scrutiny_stage嵌套字典。该模板中的row_num是什么?如果您希望我们诊断发生了什么,您需要显示真实代码。 -
你打印 (row['_id']) 并在结果字典中添加行,当然有区别。