模板引擎語法-過濾器
文章目錄
- 模板引擎語法-過濾器
- @[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)重新進行排序。
【訪問驗證】