SeonyHyun Ahn SeonyHyun Ahn - 9 days ago 6
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?

@app.route('/')
def hello_world():
return render_template('test.html')

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


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


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

Answer

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.