遍历Jinja2模板中的词典列表

时间:2019-05-11 17:50:41

标签: python flask jinja2

我尝试使用金钥模板中的键的值作为HTML属性来遍历字典列表。但是模板不会呈现任何数据。将数据传递到路由文件中的render_template函数时,我已经验证了数据正确。

我经历了许多StackOverflow问题,特别是How to iterate through a list of dictionaries in jinja template?,但无济于事。

这是我的数据结构:

[
  {
    'name': 'chicken pie',
    'image': 'chicken.jpg',
    'url': 'chicken.html'
  },
  {
    'name': 'chicken sandwich',
    'image': 'sandwich.jpg',
    'url': 'sandwich.html'
  }
]

我的模板是:

<div class="page-header">
  <h1>Recipes Matching {{ query }}</h1>
  {% for dict_item in names %}
    <div>
      <img src="{{ dict_item['image'] }}" height="100" width="100">
      <a href="{{ dict_item['url'] }}">{{ dict_item['name'] }}</a>
    </div>
  {% endfor %}
</div>

1 个答案:

答案 0 :(得分:0)

使用字典键作为属性,将结构转换为类对象列表要容易得多

class Item:
  def __init__(self, vals):
    self.__dict__ = vals

@app.route('/yourroute')
def your_route():   
  data = [{'name': 'chicken pie', 'image': 'chicken.jpg', 'url': 'chicken.html'}, {'name': 'chicken sandwich', 'image': 'sandwich.jpg', 'url': 'sandwich.html'}]
  return flask.render_template('your_template.html', names = [Item(i) for i in data])

最后,在your_template.html中:

<div class="page-header">
<h1>Recipes Matching {{ query }}</h1>
{% for dict_item in names %}
  <div>
    <img src="{{dict_item.image}}" height="100" width="100">
    <a href="{{dict_item.url}}">{{dict_item.name}}</a>
  </div>
{% endfor %}
</div>