第一种 通过调用应用程序实例的 add_template_filter
from flask import Flask, render_template
import settings
app = Flask(__name__)
app.config.from_object(settings)
@app.route('/')
def hello_world(): # put application's code here
msg = 'hello every hello world.'
return render_template('show.html', msg=msg)
# 过滤器本质也是函数
# 第一种方式
def replace_hello(value):
print('--------->', value)
value = value.replace('hello', '')
print('=======>', value)
return value.strip() # 将替换的结果返回
app.add_template_filter(replace_hello, 'replace')
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义过滤器</title>
</head>
<body>
{{ msg }}
<hr>
{{ msg|replace }}
</body>
</html>
第二种 使用装饰器完成
from flask import Flask, render_template
import settings
app = Flask(__name__)
app.config.from_object(settings)
@app.route('/')
def hello_world(): # put application's code here
msg = 'hello every hello world.'
li = [3,9,6,0,5,5,1]
return render_template('show.html', msg=msg,li=li)
# 过滤器本质也是函数
# 第一种方式
def replace_hello(value):
print('--------->', value)
value = value.replace('hello', '')
print('=======>', value)
return value.strip() # 将替换的结果返回
app.add_template_filter(replace_hello, 'replace')
# 第二种方式 装饰器
@app.template_filter('listreverse') #跟route很像
def reverse_list(li):
temp_li = list(li)
temp_li.reverse()
return temp_li
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义过滤器</title>
</head>
<body>
{{ msg }}
<hr>
{{ msg|replace }}
<hr>
{{ li }}
<hr>
{{ li|listreverse }}
</body>
</html>
# -*- codeing = utf-8 -*-
# @Time : 2021/8/20 10:28
# @Author : 二帆
# @File : settings.py
# @Software : PyCharm
ENV = 'development'
DEBUG = True
总结
1.通过flask模块中的add_template_filter 方法
步骤:
a.定义函数,带有参数和返回值
b.添加过滤器 app.add_template_filter(function,name=’’)
c.在模板中使用:{{变量 | 自定义过滤器}}
2.使用装饰器完成
a.定义函数,带有参数和返回值
b.通过装饰器完成,@app.template_filter(‘过滤器名字’)装饰
c.在模板中使用:{{变量 | 自定义过滤器}}