繁体   English   中英

遍历Jinja2模板中的词典列表

[英]Iterating over a list of dictionaries in Jinja2 template

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

我经历了许多StackOverflow问题,尤其是如何遍历Jinja模板中的词典列表? 但无济于事。

这是我的数据结构:

[
  {
    '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>

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

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM