PenguinGoHack February 2016

UndefinedError when trying to call function in Jinja templaet

In my view function, I pass a dict variable to my HTML file. tags is a dictionary which is by default {int: []}. As the value of each key is a list, I use iteritems() to show every item in the list. However, it didn't work, I got the error UndefinedError: 'tags' is undefined. Is Jinja2 able to call functions in HTML? Why didn't my code work?

return render_template('index.html', title='Home', user=user, posts=posts, tags=tags)
<div class="post-tag">
{% for key,tag in tags.iteritems() %}
<a href="#">{{tag}}</a>
{% endfor %}
</div>

Answers


Alex Hristov February 2016

Personally I've never used flask but I've used jinja2 with cherrypy. Actually your code is absolutely correct. This is how it works but what I think is happening is that the variable tags is not defined when you are rendering the template. Have a look here

All the basic datatype operations are available in jinja2. Check if tags is not being defined in some if condition that you're not entering in your particular case.

{% for k, v in dct.iteritems() %}<a href="#">{{k}}</a>{% endfor %}

outputs

<a href="#">item1</a><a href="#">item2</a>

Post Status

Asked in February 2016
Viewed 1,416 times
Voted 14
Answered 1 times

Search




Leave an answer