flask全局变量二,自定义上下文参数

如果我要在模板中一个多选菜单的项目是个变量。那么要每个视图函数读一次变量,再发送到模版中去。比如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
def get_option_item():
item = ["项目1""项目2""项目3""项目4""项目5""项目6""项目7",]
return item
#视图1
@app.route(/index1)
def index1():
item=get_option_item()
return render_template("index1.html", item=itme)
....
#视图n
@app.route(/index_n)
def index_n():
item=get_option_item()
return render_template("indexn.html", item=itme)

在模板中

1
2
3
4
5
<select>
{% for select_i in item %}
<option> select_i </option>
{% endfor %}
</select>
每个视图要读一次很烦,那么采用上下文变量的方式就很好的解决了这个问题。修改一下python代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# current_app对象是一个定义在应用上下文中的代理
from flask import current_app
app=Flask(__name__)

# 函数用@app.context_processor装饰器修饰,它是一个上下文处理器,它的作用是在模板被渲染前运行其所修饰的函数,并将函数返回的字典导入到模板上下文环境中,与模板上下文合并。
@app.context_processor
def get_option_item():
item = ["项目1""项目2""项目3""项目4""项目5""项目6""项目7",]
return dict(item=item) #注意是字典
# 视图函数不用再调用了
#视图n
@app.route(/index_n)
def index_n():
# item=get_option_item()
return render_template("indexn.html")
模板不用改变,直接就可用了。