我正在使用 Flask,在一个端点中我只是将以下字典传递给 html 文件:
app = Flask(__name__)
@app.route("/home")
def home():
q = {"id":23,
"path": '/usr/test.py',
"mynum": 22}
return render_template("home.html", query=q)
在 HTML 文件中:
{% for value in query.values() %}
<td>{{ value }}</td>
{% endfor %}
但是通过这种方式,我传递了所有键值,但我需要传递某些键值。更清楚的是,我希望 HTML 中存在这样的解决方案(如果存在):
<td>{{ query["path"] }}</td>
<td>{{ query["id"] }}</td>
<td>{{ query["mynum"] }}</td>
我也尝试过这个:
<td>{{ query.path }}</td>
<td>{{ query.id }}</td>
<td>{{ query.mynum }}</td>
但打印query.path、query.id、query.mynum
而不是值
最佳答案
在 Jinja2 模板中不循环打印字典特定键的值
如果你想打印字典的特定键,你可以使用.get()
方法。
app.py
:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/home")
def home():
q = {"id":23,"path": '/usr/test.py',"mynum": 22}
return render_template("home.html", query=q)
home.html
:
<table>
<tr>
<th>ID</th>
<th>Path</th>
<th>Number</th>
</tr>
<tr>
<td>{{ query.get("id") }}</td>
<td>{{ query.get("path") }}</td>
<td>{{ query.get("mynum") }}</td>
</tr>
</table>
输出:
如果在字典中找不到该键,它将打印 None
作为值。您还可以将默认值作为 get
方法的第二个参数传递。
例如:
{{ query.get("arsho", "Value not found") }}
关于python - 如何将Python字典的某些键和值传递给HTML脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59339757/