自定义过滤器
- 过滤器就是python中的函数,注册后就可以在模板中当作过滤器使用,下面以求余为例开发一个自定义过滤器mod
示例
- 在应用中创建templatetags目录,当前示例为”booktest/templatetags“,创建init文件,内容为空

- 在”booktest/templatetags“目录下创建filters.py文件,代码如下
#coding=utf-8
#引入注册对象
from django.template import Library
register=Library()
#使用装饰器进行注册
@register.filter
#定义求余函数mod,将value对2求余
def mod(value):
return value%2
- 在templates/booktest/guolvqi.html中,使用自定义过滤器
- 首先使用load标签引入模块
{%load filters%}


- 过滤器可以接收参数,将booktest/templatetags/filters.py中增加mod_num函数
#使用装饰器进行注册
@register.filter
#定义求余函数mod_num,将value对num求余
def mod_num(value,num):
return value%num
- 在templates/booktest/guolvqi.html中修改遍历时判断代码

