首页 > 解决方案 > 有没有更简单的方法在 Jinja2 模板中调用 JSON?

问题描述

我设法将一个 JSON 文件调用到我的路由器中并访问模板中的内容。但是,我想知道是否有更简单的方法来调用我的数据。有没有办法只打电话{{ title }},而不是{{ data["title"] }}?任何帮助将不胜感激。

router_article_02.py

@app.route('/article-02/welcome')
    def article_02_welcome():
        with app.open_resource("templates/article-02/data.json", "r" ) as data_file:
            data = json.load(data_file)

    return render_template("article-02/welcome.html", data = data)

article-02.html

<h1>{{ data["title"] }}</h1>
<div class="overline">Category: {{ data["category-type"] }}</div>

标签: pythonjsonflaskjinja2

解决方案


看起来我需要使用双星号或字典解包运算符 ( **) 表示法解包字典。

router_article_02.py

@app.route('/article-02/welcome')
def article_02_welcome():
    with app.open_resource("templates/article-02/data.json", "r" ) as data_file:
        data = json.load(data_file)

    return render_template("article-02/welcome.html", **data)

article-02.html

<h1>{{ title }}</h1>
<div class="overline">Category: {{ category_type }}</div>

推荐阅读