过滤器
语法如下:
使用管道符号|来应用过滤器,用于进行计算、转换操作,可以使用在变量、标签中。
如果过滤器需要参数,则使用冒号:传递参数。
变量|过滤器:参数
长度length,返回字符串包含字符的个数,或列表、元组、字典的元素个数。
默认值default,如果变量不存在时则返回默认值。
data|default:'默认值'
日期date,用于对日期类型的值进行字符串格式化,常用的格式化字符如下:
Y表示年,格式为4位,y表示两位的年。
m表示月,格式为01,02,12等。
d表示日, 格式为01,02等。
j表示日,格式为1,2等。
H表示时,24进制,h表示12进制的时。
i表示分,为0-59。
s表示秒,为0-59。
value|date:"Y年m月j日 H时i分s秒"
示例
1)打开booktest/views.py文件,创建视图temp_filter。
def temp_filter(request):
context={'list':BookInfo.objects.all()}
return render(request,'booktest/temp_filter.html',context)
2)打开booktest/urls.py文件,配置url。
url(r'^temp_filter/$', views.temp_filter),
3)在templates/booktest下创建temp_filter.html。
<head>
<title>过滤器</title>
</head>
<body>
图书列表如下:
<ul>
{%for book in list%}
{%if book.btitle|length > 4%}
<li style="background-color: red;">
{{book.btitle}}
---默认时间格式为:
{{book.bpub_date}}
</li>
{%else%}
<li style="background-color: green;">
{{book.btitle}}
---格式化时间为:
{{book.bpub_date|date:"Y-m-j"}}
</li>
{%endif%}
{%endfor%}
</ul>
</body>
</html>
4)运行服务器,在浏览器中输入如下网址。
http://127.0.0.1:8000/temp_filter/
浏览效果如下图:
自定义过滤器
过滤器就是python中的函数,注册后就可以在模板中当作过滤器使用,下面以求余为例开发一个自定义过滤器mod。
示例
1)在应用中创建templatetags目录,当前示例为"booktest/templatetags",创建_init_文件,内容为空。
2)在"booktest/templatetags"目录下创建filters.py文件,代码如下:
#导入Library类
from django.template import Library
#创建一个Library类对象
register=Library()
#使用装饰器进行注册
@register.filter
#定义求余函数mod,将value对2求余
def mod(value):
return value%2 == 0
3)在templates/booktest/temp_filter.html中,使用自定义过滤器。
首先使用load标签引入模块。
{%load filters%}
在遍历时根据编号判断奇偶,代码改为如下:
4)运行服务器,浏览效果如下:
过滤器可以接收参数,将booktest/templatetags/filters.py中增加mod_num函数。
#使用装饰器进行注册
@register.filter
#定义求余函数mod_num,将value对num求余
def mod_num(value,num):
return value%num
5)在templates/booktest/temp_filter.html中修改遍历时判断代码。
6)运行服务器,浏览效果如下:
注释
在模板中使用如下模板注释,这段代码不会被编译,不会输出到客户端;html注释只能注释html内容,不能注释模板语言。
1)单行注释语法如下:
{#...#}
注释可以包含任何模版代码,有效的或者无效的都可以。
{# { % if foo % }bar{ % else % } #}
2)多行注释使用comment标签,语法如下:
{%comment%}
...
{%endcomment%}