from flask import Flask,render_template

#render 模板引擎
#过滤器是个函数,也可以在后台自己设置
#创建过滤器首先要先注册
# 一个函数未定义使用会报错,所以要先定义不然会爆红
# #return返回的结果会传到前端页面,前端页面也会吧{{}}括号里面的数据传回后端
# def my_filter(n):
# print(n)
# return 11
app = Flask(__name__)
# app.add_template_filter(my_filter,"m"

#通过装饰器的形式创建过滤器,如果把一个函数装饰成
# 一个过滤器需要用注册app的形式,要把位置放到app的位置下面
@app.template_filter("m")
# def my_filter(n):
# print(n)
# return 11

def my_filter(n):
try:
n= int(n)
except Exception as e:
return "非法"
return n+10
前端代码:
{{ "a"|m }}<br>
运行结果

python过滤器_flask


@app.route("/")
def index():

return render_template("index.html",
a=1,
b=[11,222,333]
)
前端代码
{{ a }}<br>
{{ a + 10}}<br>
{{ b[0] }}<br>
运行显示为

python过滤器_模板引擎_02

 

 

 

if __name__ == '__main__':
app.run()