【问题标题】:Is there a simpler way of calling JSON in a Jinja2 template?有没有更简单的方法在 Jinja2 模板中调用 JSON?
【发布时间】:2020-05-29 19:40:31
【问题描述】:

我设法将一个 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>

【问题讨论】:

    标签: python json flask jinja2


    【解决方案1】:

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

    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>
    

    【讨论】:

      【解决方案2】:

      如果key 是有效的python 变量名,您也可以使用点. 表示法。

      data = {
          'name': 'My Name',
          'current employer': 'Google',
          'country-name': 'USA',
          'state_name': 'CA'
      }
      

      然后 {{data.name}}{{data.state_name}} 可以工作,但对于其余部分,您必须使用括号语法: {{data['country-name']}}{{data['current employer']}}

      文档

      【讨论】:

        猜你喜欢
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        • 2023-02-21
        • 2012-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多