过滤器(Filter)是一种用于对模板变量进行处理的函数。其定义方式类似于普通函数,但需要使用app.template_filter()或者特殊的装饰器@app.template_filter()
来进行修饰。
1、常用过滤器
1)自定义过滤器——函数形式
#通过函数的形式定义过滤器
def replace_hello(value):
value=value.replace('hello','') #该过滤器主要功能:将字符串value里边的hello全部替换
return value
#以下的代码将 replace_hello 定义为一个过滤器,过滤器的名字为"repale"
app.add_template_filter(replace_hello,'replace')
过滤器的使用:
@app.route('/hello')
def hello_world():
msg='hello world'
return render_template('define_filter.html',msg_temp=msg)
在render_template()函数中,msg_temp作为html里边的一个变量传入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义过滤器</title>
</head>
<body>
{{ msg_temp|replace_hello }}
</body>
</html>
在{{ msg_temp|replace_hello }}中,msg_temp作为过滤器的参数传入进去,最后过滤器将进行删除字符串中"hello"的操作,返回"world",在html网页中则会显示“world”。
自定义过滤器——装饰器方式
#通过装饰器定义过滤器
@app.template_filter('list_reverse')
def reverse_list(li):
temp_li=list(li)
temp_li.reverse()
return temp_li
这个定义的过滤器的名字就是 list_reverse ,返回值是所传入列表的逆序排列,使用过滤器的方式依然是 {{ 传入参数 | 过滤器名字 }} 的方式,使用的环境是在html模板中使用。