模板引擎语法-过滤器
文章目录
- 模板引擎语法-过滤器
- @[toc]
- 1.default过滤器
- 2.default_if_none过滤器
- 3.length过滤器
- 4.addslashes过滤器
- 5.capfirst过滤器
- 6.cut过滤器
- 7.date过滤器
- 8.dictsort过滤器
文章目录
- 模板引擎语法-过滤器
- @[toc]
- 1.default过滤器
- 2.default_if_none过滤器
- 3.length过滤器
- 4.addslashes过滤器
- 5.capfirst过滤器
- 6.cut过滤器
- 7.date过滤器
- 8.dictsort过滤器
1.default过滤器
default过滤器用于设置默认值。default过滤器对于变量的作用:如果变量为false或“空”,则使用给定的默认值:否则使用变量自己的值。
文件路径【TmplSite/gramapp/views.py】
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader# Create your views here.def index(request):return HttpResponse("Hello, Django! You're at the gramapp index.")def filters(request):context = {}context['title'] = "Django Template Grammar"context['filters'] = "filters"context['default'] = "default"context['default_nothing'] = ""template = loader.get_template('gramapp/filters.html')return HttpResponse(template.render(context, request))
【代码分析】
在变量context中添加了第一个属性default,并赋值为字符串“default”。
在变量context中添加了第二个属性default_nothing,并赋值为空字符串。
文件路径【TmplSite/gramapp/templates/gramapp/filters.html】
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/><title>{{ title }}</title>
</head>
<body><p class="middle">Hello, this is a template tag <b>{{ filters }}</b> page!
</p>
<p class="middle">filters - default:<br><br>{{ default | default:"nothing" }}<br><br>{{ default_nothing | default:"nothing" }}<br><br>
</p></body>
</html>
【代码分析】
对变量default使用了default过滤器(默认值为字符串“nothing”)。
对变量default_nothing再次使用了同样的default过滤器(默认值为字符串“nothing”)
文件路径【TmplSite/gramapp/urls.py】
from django.urls import path
from . import viewsurlpatterns = [path('', views.index, name='index'),path('filters/', views.filters, name='filters'),
]
【访问验证】
变量default经过default过滤器处理后,仍旧输出了自身定义的值,因为变量default的值不为空。而变量default_nothing经过default过滤器处理后,输出了过滤器定义的值nothing,这是因为变量default_nothing的值定义为空。
2.default_if_none过滤器
default_if_none过滤器对于变量的作用:如果变量为None,则使用给定的默认值;否则,使用变量自己的值。
文件路径【TmplSite/gramapp/views.py】
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader# Create your views here.def index(request):return HttpResponse("Hello, Django! You're at the gramapp index.")def filters(request):context = {}context['title'] = "Django Template Grammar"context['filters'] = "filters"context['default'] = "default"context['defaultifnone'] = Nonetemplate = loader.get_template('gramapp/filters.html')return HttpResponse(template.render(context, request))
【代码分析】
在变量context中添加了第一个属性default,并赋值为字符串“default”。
在变量context中添加了第二个属性defaultifnone,并赋值为None。
文件路径【TmplSite/gramapp/templates/gramapp/filters.html】
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/><title>{{ title }}</title>
</head>
<body><p class="middle">Hello, this is a template tag <b>{{ filters }}</b> page!
</p>
<p class="middle">filters - default_if_none:<br><br>{{ default | default_if_none:"var is None!" }}<br><br>{{ defaultifnone | default_if_none:"var is None!" }}<br><br>
</p></body>
</html>
【代码分析】
对变量default使用了default_if_none过滤器(默认值为字符串“var is None!”)。
对变量defaultifnone使用了同样的default_if_none过滤器(默认值同样为字符串“var is None!”)。
【访问验证】
变量default经过default_if_none过滤器处理后,仍旧输出了自身定义的值,因为变量default的值不为None。而变量defaultifnone经过default_if_none过滤器处理后,输出了过滤器定义的值"var is None!",这是因为变量defaultifnone的值定义为None。
3.length过滤器
该过滤器可以获取字符串、列表、元组、和字典等对象类型的长度。
文件路径【TmplSite/gramapp/views.py】
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader# Create your views here.def index(request):return HttpResponse("Hello, Django! You're at the gramapp index.")def filters(request):context = {}context['title'] = "Django Template Grammar"context['filters'] = "filters"context['lenAlpha1'] = "abcde"context['lenAlpha2'] = ['a', 'b', 'c', 'd', 'e']context['lenAlpha3'] = ('a', 'b', 'c', 'd', 'e')context['lenAlphaDic'] = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }template = loader.get_template('gramapp/filters.html')return HttpResponse(template.render(context, request))
【代码分析】
在变量context中添加了第一个属性lenAlpha1,并赋值为字符串“abcde”。
在变量context中添加了第二个属性lenAlpha1,并赋值为一个列表[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]。
在变量context中添加了第三个属性lenAlpha3,并赋值为一个元组(‘a’, ‘b’, ‘c’, ‘d’, ‘e’)。
在变量context中添加了第四个属性lenAlphaDic,并赋值为一个字典{ ‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5 }。
文件路径【TmplSite/gramapp/templates/gramapp/filters.html】
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/><title>{{ title }}</title>
</head>
<body><p class="middle">Hello, this is a template tag <b>{{ filters }}</b> page!
</p>
<p class="middle">filters - length:<br><br>{{ lenAlpha1 }} length : {{ lenAlpha1 | length }}<br><br>{{ lenAlpha2 }} length : {{ lenAlpha2 | length }}<br><br>{{ lenAlpha3 }} length : {{ lenAlpha3 | length }}<br><br>{{ lenAlphaDic }} length : {{ lenAlphaDic | length }}<br><br>
</p></body>
</html>
【代码分析】
分别通过过滤器length对一组变量(字符串类型、列表类型、元组类型和字典类型)进行过滤操作。
【访问验证】
变量(字符串类型、列表类型、元组类型和字典类型)经过length过滤器处理后,输出的长度均为5。
4.addslashes过滤器
该过滤器会在引号前面添加反斜杠字符(\),常用于字符转义。
文件路径【TmplSite/gramapp/views.py】
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader# Create your views here.def index(request):return HttpResponse("Hello, Django! You're at the gramapp index.")def filters(request):context = {}context['title'] = "Django Template Grammar"context['filters'] = "filters"context['add_slashes'] = "This's a django app."template = loader.get_template('gramapp/filters.html')return HttpResponse(template.render(context, request))
【代码分析】
在变量context中添加了一个属性add_slashes,并赋值为一个字符串(包含有单引号)。
文件路径【TmplSite/gramapp/templates/gramapp/filters.html】
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/><title>{{ title }}</title>
</head>
<body><p class="middle">Hello, this is a template tag <b>{{ filters }}</b> page!
</p>
<p class="middle">filters - addslashes:<br><br>{{ add_slashes }} addslashes {{ add_slashes | addslashes }}<br><br>
</p></body>
</html>
【代码分析】
通过过滤器addslashes对变量add_slashes进行过滤操作,在单引号前面插入反斜杠字符(\)。
【访问验证】
5.capfirst过滤器
该过滤器会将首字母大写。而如果第一个字符不是字母,则该过滤器将不会生效。
文件路径【TmplSite/gramapp/views.py】
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader# Create your views here.def index(request):return HttpResponse("Hello, Django! You're at the gramapp index.")def filters(request):context = {}context['title'] = "Django Template Grammar"context['filters'] = "filters"context['cap_first'] = "django"context['cap_first_0'] = "0django"template = loader.get_template('gramapp/filters.html')return HttpResponse(template.render(context, request))
【代码分析】
在变量context中添加了第一个属性cap_first,并赋值为一个小写字符串(“django”)。
在变量context中添加了第二个属性cap_first_0,并赋值为一个字符串(“0django”),首字符为数字0。
文件路径【TmplSite/gramapp/templates/gramapp/filters.html】
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/><title>{{ title }}</title>
</head>
<body><p class="middle">Hello, this is a template tag <b>{{ filters }}</b> page!
</p>
<p class="middle">filters - capfirst:<br><br>{{ cap_first }} cap_first {{ cap_first | capfirst }}<br><br>{{ cap_first_0 }} cap_first {{ cap_first_0 | capfirst }}<br><br>
</p></body>
</html>
【代码分析】
通过capfirst过滤器对变量cap_first进行过滤操作,将首字符的小写字母转换为大写字母。
通过capfirst过滤器对变量cap_first进行过滤操作,测试一下该过滤器对首字符为数字的字符串是否有效。
【访问验证】
6.cut过滤器
该过滤器会移除变量中所有的与给定参数相同的字符串。
文件路径【TmplSite/gramapp/views.py】
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader# Create your views here.def index(request):return HttpResponse("Hello, Django! You're at the gramapp index.")def filters(request):context = {}context['title'] = "Django Template Grammar"context['filters'] = "filters"context['cut_space'] = "This is a cut filter."template = loader.get_template('gramapp/filters.html')return HttpResponse(template.render(context, request))
【代码分析】
在变量context中添加了一个属性cut_space,并赋值为一个带有空格的字符串。
文件路径【TmplSite/gramapp/templates/gramapp/filters.html】
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/><title>{{ title }}</title>
</head>
<body><p class="middle">Hello, this is a template tag <b>{{ filters }}</b> page!
</p>
<p class="middle">filters - cut:<br><br>{{ cut_space }} cut {{ cut_space | cut:" " }}<br><br>
</p></body>
</html>
【代码分析】
通过cut过滤器对变量cut_space进行过滤操作,并定义过滤器参数为空格字符(“”)。
【访问验证】
变量在经过处理后,字符串中的空格被全部删除了。
7.date过滤器
该过滤器会根据给定格式对一个日期变量进行格式化操作。date过滤器定义了若干个格式化字符,下面介绍几个比较常见的格式化字符:
- b:表示月份,小写字母形式(3个字母格式)。例如,jan、may、oct等。
- c:表示ISO 8601时间格式。例如,2020-08-08T08:08:08.000888+08:00。
- d:表示日期(带前导零的2位数字)。例如,01~31。
- D:表示星期几。例如,Mon、Fri、Sun等。
- f:表示时间。例如,9:30。
- F:表示月份(文字形式)。例如,January。
- h:表示12小时格式。例如,1~12。
- H:表示24小时格式。例如,0~23。
- i:表示分钟。例如,00~59。
- j:表示没有前导零的日期。例如,1~31。
- 1:表示星期几(完整英文名)。例如,Friday。
- m:表示月份(带前导零的2位数字)。例如,01~12。
- M:表示月份(3个字母的文字格式)。例如,Jan。
- r:表示RFC5322格式化日期。例如,Thu,08 Dec 2020 08:08:08 +0200。
- s:表示秒(带前导零的2位数字)。例如,00~59。
- S:表示日期的英文序数后缀(两个字符)。例如,st、nd、rd、th。
- U:表示自Unix Epoch(1970年1月1日00:00:00 UTC)以来的秒数。
- y:表示年份(2位数字)。例如,99。
- Y:表示年份(4位数字)。例如,1999
文件路径【TmplSite/gramapp/views.py】
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader
from datetime import datetime, date# Create your views here.def index(request):return HttpResponse("Hello, Django! You're at the gramapp index.")def filters(request):context = {}context['title'] = "Django Template Grammar"context['filters'] = "filters"context['now'] = datetime.now()template = loader.get_template('gramapp/filters.html')return HttpResponse(template.render(context, request))
【代码分析】
通过import引入了datetime模块。
在变量context中添加了一个属性now,并通过datetime对象获取了当前时间。
文件路径【TmplSite/gramapp/templates/gramapp/filters.html】
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/><title>{{ title }}</title>
</head>
<body><p class="middle">Hello, this is a template tag <b>{{ filters }}</b> page!
</p>
<p class="middle">filters - date:<br><br>{{ now | date }}<br><br>{{ now | date:"SHORT_DATE_FORMAT" }}<br><br>{{ now | date:"D d M Y" }}<br><br>{{ now | date:"D d M Y H:i" }}<br><br>{{ now | date:"c" }}<br><br>{{ now | date:"r" }}<br><br>
</p></body>
</html>
【代码分析】
使用了不带参数的date过滤器。
使用了带参数"SHORT_DATE_FORMAT"的date过滤器。
使用了带参数"D d M Y"的date过滤器。
使用了带参数"D d M Y H:i"的date过滤器。
使用了带参数"c"的date过滤器。
使用了带参数"r"的date过滤器。
【访问验证】
变量在经过处理后,在页面中显示了不同格式的日期和时间。
8.dictsort过滤器
该过滤器会接受一个包含字典元素的列表,并返回按参数中给出的键进行排序后的列表。
文件路径【TmplSite/gramapp/views.py】
from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader
from datetime import datetime, date# Create your views here.def index(request):return HttpResponse("Hello, Django! You're at the gramapp index.")def filters(request):context = {}context['title'] = "Django Template Grammar"context['filters'] = "filters"context['dict_sort'] = [{'name': 'king', 'age': 39},{'name': 'tina', 'age': 25},{'name': 'cici', 'age': 12},]template = loader.get_template('gramapp/filters.html')return HttpResponse(template.render(context, request))
【代码分析】
在变量context中添加了一个属性dict_sort,并赋值为一个字典类型的对象。
文件路径【TmplSite/gramapp/templates/gramapp/filters.html】
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/><title>{{ title }}</title>
</head>
<body><p class="middle">Hello, this is a template tag <b>{{ filters }}</b> page!
</p>
<p class="middle">filters - dictsort:<br><br>original dict:<br>{{ dict_sort }}<br><br><br>dictsort by 'name':<br>{{ dict_sort | dictsort:"name" }}<br><br><br>dictsort by 'age':<br>{{ dict_sort | dictsort:"age" }}<br><br><br>
</p></body>
</html>
【代码分析】
输出了原始字典类型变量dict_sort的内容。
通过dict_sort过滤器(参数定义为“name”)对字典类型变量dict_sort进行了过滤操作,表示对变量dict_sort按照键(name)重新进行排序。
通过dict_sort过滤器(参数定义为“age”)对字典类型变量dict_sort进行了过滤操作,表示对变量dict_sort按照键(age)重新进行排序。
【访问验证】