SeonyHyun Ahn SeonyHyun Ahn - 6 months ago 51
Python Question

Calling template_filter function in flask only once?

I have a simple filter that should print out what value is passed to it. I created a simple template to use it. The first time the page is viewed, the value is printed in the terminal, but after that the template is rendered but it is not printed again. Why is the filter only being called once?

def hello_world():
return render_template('test.html')

def allow_menu(menu):
print('allow_menu : {}'.format(menu))
return menu == 'test'

{% if 'test' | allow_menu %}ok{% endif %}

$ python
* Running on (Press CTRL+C to quit)
allow_menu : test - - [31/Aug/2015 15:50:46] "GET / HTTP/1.1" 200 - - - [31/Aug/2015 15:50:47] "GET / HTTP/1.1" 200 -


The first time a template file is loaded, Jinja compiles it and caches the result internally. Since you are always passing the constant 'test' to the filter, Jinja optimizes this by evaluating it during compilation, rather than during each render.

The first time the template is used, the filter is called. Subsequent renders use the cached version with the evaluated constsnt and the function is not called. If the value passed to the filter was not constant, the filter would be evaluated during each render instead.