1、通过flask模块中的add_template_filter方法
- 定义函数,带有参数和返回值
- 添加过滤器,app.add_template_filter(function,name='')
- 在模版中使用:{{变量|自定义过滤器}}
2、使用装饰器完成
- 定义函数,带有参数和返回值
- 添加过滤器,@add_template_filter('过滤器名字')
- 在模版中使用:{{变量|自定义过滤器}}
py文件
from flask import Flask from flask import make_response, request, render_template,redirect,url_for import setting,json app = Flask(__name__) app.config.from_object(setting) @app.route('/') def hello_world(): msg = 'hello everyone hello world' li = [3,4,7,2,1,5,9] return render_template('test.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') def reverse_list(li): tem_li = list(li) tem_li.reverse() return tem_li if __name__ == '__main__': app.run(host='127.0.0.1', port=5000)
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>自定义过滤器</title> </head> <body> {{ msg }} <hr> {{ msg|replace }} <hr> {{ li }} {{ li|listreverse }} </body> </html>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。