Reputation: 13
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>
Upvotes: 0
Views: 3167
Reputation: 71451
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>
Upvotes: 3