python - 如何将Python字典的某些键和值传递给HTML脚本

标签 python html flask

我正在使用 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>

输出:

Dictionary key value in Jinja2 template

如果在字典中找不到该键,它将打印 None 作为值。您还可以将默认值作为 get 方法的第二个参数传递。

例如:

{{ query.get("arsho", "Value not found") }}

关于python - 如何将Python字典的某些键和值传递给HTML脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59339757/

相关文章:

python - 使用公式将行添加到数据框

html - 使用 CSS 强制 HTML textarea 使用等宽字体

html - 使用 html5 在浏览器中可视化 mjpeg-over-http 流

python - Flask:将用户重定向到 html 页面的特定部分

flask - login_required 装饰器在 POST 之前进行 GET。然后 Post 请求中没有 'next'

Python:在构造默认值时使用姊妹参数

python - 如何获取网页的html dom及其框架

Python:列表代数简化

javascript - 使用 JavaScript 写入 <div> 元素的替代方法?

python - json.dumps 与 flask.jsonify