使用jinja2模板显示json

时间:2017-10-19 13:28:42

标签: python html json flask jinja2

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

我已经包含了我的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 tempate文件:

<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."
} }

1 个答案:

答案 0 :(得分:0)

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>

您将获得如下输出:

enter image description here