简体   繁体   中英

Iterating over a list of dictionaries in Jinja2 template

I am attempting to loop through a list of dictionaries, using the values of the keys as HTML attributes within the jinja template. But the template doesn't render any of the data. I've verified the data is correct when I pass it in to the render_template function in the routes file.

I've gone through a number of StackOverflow questions, notably How to iterate through a list of dictionaries in jinja template? but to no avail.

Here's my data structure:

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

And my template is:

<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>

It is much easier to convert your structure to a list of class objects, with the dictionary keys as attributes:

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])

Lastly, in 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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