在烧瓶中只调用一次template_filter函数? [英] Calling template_filter function in flask only once?

查看:122
本文介绍了在烧瓶中只调用一次template_filter函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的过滤器,应该打印出什么值传递给它。我创建了一个简单的模板来使用它。第一次查看页面时,该值将被打印在终端中,但在此之后,模板将被渲染,但不会再次打印。为什么过滤器只被调用一次?

  @ 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 
*在http://0.0.0.0:9876/上运行(按下CTRL + C退出)
allow_menu:test
10.10.2.62 - - [31 / Aug / 2015 15:50:46]GET / HTTP / 1.1200 -
10.10.2.62 - - [31 / Aug / 2015 15:50:47]GET / HTTP / 1.1200 -


解决方案

编译它并在内部缓存结果。由于您总是将常量'test'传递给过滤器,因此Jinja会在编译过程中对其进行优化,而不是在每次渲染过程中进行评估。

第一次使用模板时,过滤器被调用。随后的渲染使用与被评估的constsnt缓存的版本,该函数不被调用。如果传递给过滤器的值不是常量,那么将在每个渲染过程中评估过滤器。


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 - 

解决方案

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.

这篇关于在烧瓶中只调用一次template_filter函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆