How to get a Python dict into an HTML template using Flask/Jinja2 -
i'm trying use python dict in html file. dictionary passed html template through render_template
function in flask.
this format of dict:
dict1[counter] = { 'title': l.gettitle(), 'url': l.getlink(), 'img': l.getimg() }
then in html template in want iterate through dict:
{% l in result.iteritems() %} <div class="link"> <a href="{{ l.url }}"> {{l.title}}</a> <img src="{{ l.img }}" width="100" height="100"> </div> {% endfor %}
i don't know problem is, since there no error log in flask.
the problem you’re iterating on iteritems()
, iterator of (key, value) pairs. means l
variable tuple, not dictionary. want iterate on itervalues()
instead. update template code follows:
{% l in result.itervalues() %} <div class="link"> <a href="{{ l.url }}"> {{l.title}}</a> <img src="{{ l.img }}" width="100" height="100"> </div> {% endfor %}
i believe should behaviour want.
note return values in random order (as iterating on dictionary random). if wanted sort key, modify template follows:
{% key in result.iterkeys()|sort %} <div class="link"> {%- set val=result[key] %} <a href="{{ val.url }}"> {{val.title}}</a> <img src="{{ val.img }}" width="100" height="100"> </div> {% endfor %}
here iterate on sorted keys, associated value, , drop template.
you swap out sort
filter filter applies ordering of choice.
here’s minimal example demonstrates new template:
template_str = """ {% l in result.itervalues() %} <div class="link"> <a href="{{ l.url }}"> {{l.title}}</a> <img src="{{ l.img }}" width="100" height="100"> </div> {% endfor %} """ jinja2 import template template = template(template_str) class democlass(object): def gettitle(self): return "hello world" def getlink(self): return "google.co.uk" def getimg(self): return "myimage.png" class democlass2(object): def gettitle(self): return "foo bar" def getlink(self): return "stackoverflow.com" def getimg(self): return "a_photo.jpeg" l = democlass() m = democlass2() dict1 = {} dict1['l'] = { 'title': l.gettitle(), 'url': l.getlink(), 'img': l.getimg() } dict1['m'] = { 'title': m.gettitle(), 'url': m.getlink(), 'img': m.getimg() } print template.render(result=dict1)
here's html returns:
<div class="link"> <a href="stackoverflow.com"> foo bar</a> <img src="a_photo.jpeg" width="100" height="100"> </div> <div class="link"> <a href="google.co.uk"> hello world</a> <img src="myimage.png" width="100" height="100"> </div>