当前位置: 首页 > news >正文

模板引擎语法-过滤器

模板引擎语法-过滤器

文章目录

  • 模板引擎语法-过滤器
    • @[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)重新进行排序。

【访问验证】

在这里插入图片描述

相关文章:

  • Spring进阶篇
  • Github 2025-04-26 Rust开源项目日报Top10
  • 自动化测试实战篇
  • SVN 安装指南
  • WebAssembly全栈革命:在Rust与JavaScript之间构建高性能桥梁
  • ARM架构的微控制器总线矩阵
  • k8s学习记录(四):节点亲和性
  • Postman脚本处理各种数据的变量
  • 高级 SQL 技巧:提升数据处理能力的实用方法
  • AutoSAR从概念到实践系列之MCAL篇(二)——Mcu模块配置及代码详解(下)
  • Ollama平替!LM Studio本地大模型调用实战
  • 【那些年踩过的坑】Docker换源加速详细教程(截至2025年4月)
  • 【10分钟读论文】Power Transmission Line Inspections电力视觉水文
  • vue3学习之防抖和节流
  • 二叉搜索树的实现与应用场景
  • 推荐几个免费提取音视频文案的工具(SRT格式、通义千问、飞书妙记、VideoCaptioner、AsrTools)
  • 线性代数(一些别的应该关注的点)
  • GoFly快速开发框架新增UI素材库-帮助开发者快速开发管理后台UI基于ArcoDesign框架开发
  • 深入理解网络安全中的加密技术
  • 月之暗面开源 Kimi-Audio-7B-Instruct,同时支持语音识别和语音生成
  • 一周人物|卡鲁等入围英国特纳奖,李学明新展中国美术馆
  • 商务部:一季度我国服务贸易较快增长,进出口总额同比增8.7%
  • 新造古镇丨上海古镇朱家角一年接待164万境外游客,凭啥?
  • 全过程人民民主研究基地揭牌,为推动我国民主政治建设贡献上海智慧
  • 体坛联播|利物浦提前4轮夺冠,安切洛蒂已向皇马更衣室告别
  • 经济日报:多平台告别“仅退款”,规则调整有何影响