【问题标题】:Using jinja2 templates to display json使用jinja2模板显示json
【发布时间】:2018-03-31 13:25:32
【问题描述】:

我有一个使用 jinga2 模板和 Json 设置的烧瓶网络应用程序。我正在尝试在我的 html 模板中显示存储在 json 文件中的数据。理想情况下,我希望它显示并看起来像 html 中的列表。该页面应该以配方格式显示 json,例如 step my step 但我似乎无法让它工作。

我已经包含了我的 python 文件、json 和 html 模板来帮助重现问题。

这是我的 python 文件:

@app.route('/recipes/pumpkin_pie/')
@app.route('/recipes/halloween/pumpkin_pie/')
def pumpkin_pie():
  recipes = []
  with open('recipes.json', 'r') as f:
     recipes = json.load(f)
     f.close()
  print recipes

  p = {}
  for item in recipes:
     if item['name'] == "pumpkin pie":
       print item
       p = item
       print p

  return render_template('pumpkin_pie.html', pumpkin=p)

这是我的 html 模板文件:

<div class="container">
<div class="ingredients">
    <p>{{ pumpkin.ingredients }}</p>
</div>
<div class="method">
    <ul>
    {% for result in pumpkin %}
        {% for methods in result %}
            <li>{{pumpkin.methods }}</li>
        {% endfor %}
    {% endfor %}
    </ul>
</div>

这是我的 json 文件:

{
"name": "pumpkin pie",
"ingredients": [" large eggs plus 1 yolk", "1 tsp ground cinnamon"],
"methods": {
    "1": "Pre-heat the oven to 200C/400F/Gas 6",
    "2": "If using a shop bought sweet crust pastry case, use one that is 23cm/9in diameter and 4cm/1.5in deep. If using your own pastry, roll it out and use it to line a 23cm/9in pie plate (not loose bottomed). Bake the pastry case blind for 20 minutes."
} }

【问题讨论】:

  • 究竟是什么不工作?
  • 这样显示json方法并多次显示 {u'1': u'Pre-heat the oven to 200C/400F/Gas 6', u'2': u'If using一家商店买了甜皮糕点盒,用的是直径 23 厘米/9 英寸,深 4 厘米/1.5 英寸的。如果使用您自己的糕点,将其擀开并用它来排列一个 23 厘米/9 英寸的馅饼盘(底部不松散)。将糕点盒盲烤 20 分钟。'}

标签: python html json flask jinja2


【解决方案1】:

JSON 文件中,您没有对象数组。相反,你只有一个对象。因此,在 Python 中将其假设为对象数组进行迭代不会给出期望的输出。

将python文件更新为:

@app.route('/recipes/pumpkin_pie/')
@app.route('/recipes/halloween/pumpkin_pie/')
def pumpkin_pie():
    recipes = []
    with open('recipes.json', 'r') as f:
        recipes = json.load(f)
        f.close()
    return render_template('pumpkin_pie.html', pumpkin=recipes)

模板文件为:

<div class="container">
<div class="ingredients">
    <h3>Ingredients</h3>
    <ul>
        {% for ingredient in pumpkin.ingredients %}
            <li>{{ ingredient }}</li>
        {% endfor %}
    </ul>
</div>
<div class="method">
    <h3>Methods</h3>
    <ul>
        {% for key in pumpkin.methods %}
            <li>{{ pumpkin.methods[key] }}</li>
        {% endfor %}
    </ul>
</div>

你会得到如下输出:

【讨论】:

    猜你喜欢
    • 2012-07-27
    • 1970-01-01
    • 2014-06-08
    • 2018-07-15
    • 2020-11-21
    • 1970-01-01
    • 2011-06-15
    • 2016-03-22
    • 2019-07-01
    相关资源
    最近更新 更多