django自定义过滤器(其实就是一个函数)的步骤:
- 在应用下建一个python package,名字一定是也只能是templatetags。
- 在templatetags包下新建一个文件,文件名可由自己定义。比如我们在此定义一个判断是否为偶数的过滤器,过滤器函数最少一个参数,最多两个参数, 使用如下:filters.py
from django.template import Library
#创建一个Library类的实例对象
register = Library()
#带一个参数的过滤器
@register.filter
def mod(num):
return num % 2 == 0
#带2个参数的过滤器
@mod_val(num, val):
return num%val == 0
- 在需要自定义标签的模板上,{% load filters %}, 其中filters是自定义的文件名,使用如下:| 前面的数据作为第一个参数,多个参数则需要在自定义过滤器后面加:,使用如下
<!DOCTYPE html>
<html lang="en">
{% load filters %}
<head>
<meta charset="UTF-8">
<title>模板标签</title>
<style>
.yellow {
background-color: yellow;
}
.orange {
background-color: orange;
}
</style>
</head>
<body>
<h2>带一个参数的自定义过滤器</h2>
<ul>
{% for b in books %}
{% if b.id|mod %}
<li class="yellow">{{ forloop.counter }} ----{{ b.btitle }}</li>
{% else %}
<li class="orange">{{ forloop.counter }} ----{{ b.btitle }}</li>
{% endif %}
{% endfor %}
</ul>
<hr/>
<h2>带2个参数的自定义过滤器</h2>
<ul>
{% for b in books %}
{% if b.id|mod_val:3 %}
<li class="yellow">{{ forloop.counter }} ----{{ b.btitle }}</li>
{% else %}
<li class="orange">{{ forloop.counter }} ----{{ b.btitle }}</li>
{% endif %}
{% endfor %}
</ul>
<hr/>
</body>
</html>