python - 有没有更简单的方法在 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>
解决方案
看起来我需要使用双星号或字典解包运算符 ( **
) 表示法解包字典。
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>
推荐阅读
- html - SVG 图像在 ie 中没有获得视口的全宽
- odoo - 如何通过 ODOO 中的某些身份验证重定向到 URL
- javascript - 我们如何从 jquery 中的 keyup 获取 val
- python - Tkinter - 显示按钮
- python - 删除python数据框中的异常值
- php - 如何在 wordpress 管理页面(预订)中添加分页以及如何将我的预订打印为 pdf
- reactjs - 区块链和 ReactJs 用户界面
- javascript - 如何在 javascript 中获取 html 元素的邻居?
- python - 在不同的行中显示 div 中的 html 文本
- c# - 我们如何在没有 ASP.NET 的情况下使用带有 JS 框架的 C# 来开发单页应用程序?