flask提供了局部和全局两种方式的数据,用于模板渲染
@app.template_global()
@app.template_filter()
如果函数上面有这两个装饰器之一,那么该函数就可以全局模板渲染
from flask import Flask, render_template, Markup
app = Flask(__name__)
app.debug = True
def func(arg):
return arg + 1
@app.template_global()
def global_template(arg1, arg2):
"""
@app.template_global 装饰了global_template 这个方法,
那么, global_template就是一个全局的模板,随便哪儿都可以用、
:param arg1:
:param arg2:
:return:
"""
return arg1 + arg2
@app.template_filter()
def filter_template(arg1,arg2,arg3):
"""
也是一个全局模板,但是使用方法与template_global不同
:param arg1:
:param arg2:
:param arg3:
:return:
"""
return arg1+arg2+arg3
@app.route('/user')
def index():
context = {'users': ['小明', '小强'],
'txt': '<input type = "text" /input>',
# Markup 表示可信任
'html': Markup('<input type = "text" /input>'),
'func': func
}
return render_template("user.html", **context)
if __name__ == '__main__':
app.run()
视图user.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ users.0 }}
{{ users[1] }}
{#以字符串的形式展示,防止了xss攻击 #}
{{ txt }}
{#信任#}
{{ txt| safe }}
{{ html }}
{{ func(8) }}
{{ global_template(1,2) }}
{#真是有点扯蛋#}
{{ 1| filter_template(2,3) }}
</body>
</html>
日拱一卒无有尽,功不唐捐终入海
浙公网安备 33010602011771号