模板引擎语法-过滤器

模板引擎语法-过滤器

文章目录

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

【访问验证】

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/77518.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

make学习三:书写规则

系列文章目录 Make学习一&#xff1a;make初探 Make学习二&#xff1a;makefile组成要素 文章目录 系列文章目录前言默认目标规则语法order-only prerequisites文件名中的通配符伪目标 Phony Targets没有 Prerequisites 和 recipe内建特殊目标名一个目标多条规则或多个目标共…

网络安全技能大赛B模块赛题解析Server12环境

已知靶机存在⽹站系统&#xff0c;使⽤Nmap⼯具扫描靶机端⼝&#xff0c;并将⽹站服务的端⼝号作为Flag &#xff08;形式&#xff1a;Flag字符串&#xff09;值提交 使用nmap扫描目标靶机网站服务的端口号为8089 Falg&#xff1a;8089 访问⽹站/admin/pinglun.asp⻚⾯&#…

1、Linux操作系统下,ubuntu22.04版本切换中英文界面

切换中英文界面的方法很多&#xff0c;我也是按照一个能用的方法弄过来并且记录&#xff0c; 1.如果刚开始使用Ubuntu环境&#xff0c;桌面的语言环境为英文&#xff0c;需要安装中文简体的字体包 打开桌面终端&#xff0c;输入 sudo apt install language-pack-zh-hans lan…

SmolVLM2: The Smollest Video Model Ever(六)

继续微调 微调视频的代码如下&#xff1a; # 此Python文件用于对SmolVLM2进行视频字幕任务的微调 # 导入所需的库 import os os.environ["CUDA_VISIBLE_DEVICES"] "1" import torch from peft import LoraConfig, prepare_model_for_kbit_training, get…

Spring Boot安装指南

&#x1f516; Spring Boot安装指南 &#x1f331; Spring Boot支持两种使用方式&#xff1a; 1️⃣ 可作为常规Java开发工具使用 2️⃣ 可作为命令行工具安装 ⚠️ 安装前提&#xff1a; &#x1f4cc; 系统需安装 Java SDK 17 或更高版本 &#x1f50d; 建议先运行检查命令…

数据结构(七)---链式栈

#### 链式栈实现 ##### linkstack.h #ifndef _LINKSTACK_H #define _LINKSTACK_H // 引入相关的库文件 #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义元素类型的别名 typedef int DATA; //定义链式栈节点 typedef struct node { …

【Spring Boot】Maven中引入 springboot 相关依赖的方式

文章目录 Maven中引入 springboot 相关依赖的方式1. 不使用版本管理&#xff08;不推荐&#xff09;2、使用版本管理&#xff08;推荐&#xff09;2.1 继承 spring-boot-starter-parent2.2 使用 spring-boot-dependencies 自定义父工程2.3引入 spring-framework-bom Maven中引…

DataStreamAPI实践原理——快速上手

引入 通过编程模型&#xff0c;我们知道Flink的编程模型提供了多层级的抽象&#xff0c;越上层的API&#xff0c;其描述性和可阅读性越强&#xff0c;越下层API&#xff0c;其灵活度高、表达力越强&#xff0c;多数时候上层API能做到的事情&#xff0c;下层API也能做到&#x…

WPF 图片文本按钮 自定义按钮

效果 上面图片,下面文本 样式 <!-- 图片文本按钮样式 --> <Style x:Key="ImageTextButtonStyle" TargetType="Button"><Setter Property="Background" Value="Transparent"/><Setter Property="BorderTh…

驱动开发硬核特训 · Day 22(上篇): 电源管理体系完整梳理:I2C、Regulator、PMIC与Power-Domain框架

&#x1f4d8; 一、电源子系统总览 在现代Linux内核中&#xff0c;电源管理不仅是系统稳定性的保障&#xff0c;也是实现高效能与低功耗运行的核心机制。 系统中涉及电源管理的关键子系统包括&#xff1a; I2C子系统&#xff1a;硬件通信基础Regulator子系统&#xff1a;电源…

设计模式全解析:23种经典设计模式及其应用

创建型模式 1. 单例模式&#xff08;Singleton Pattern&#xff09; 核心思想&#xff1a;确保一个类只有一个实例&#xff0c;并提供一个全局访问点。适用场景&#xff1a;需要共享资源的场景&#xff0c;如配置管理、日志记录等。 public class Singleton {// 静态变量保存…

力扣热题100题解(c++)—矩阵

73.矩阵置零 给定一个 m x n 的矩阵&#xff0c;如果一个元素为 0 &#xff0c;则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。 int m matrix.size(); // 行数int n matrix[0].size(); // 列数bool firstRowZero false; // 标记第一行是否包含 0bool f…

本地部署DeepSeek-R1(Dify升级最新版本、新增插件功能、过滤推理思考过程)

下载最新版本Dify Dify1.0版本之前不支持插件功能&#xff0c;先升级DIfy 下载最新版本&#xff0c;目前1.0.1 Git地址&#xff1a;https://github.com/langgenius/dify/releases/tag/1.0.1 我这里下载到老版本同一个目录并解压 拷贝老数据 需先停用老版本Dify PS D:\D…

PostSwigger Web 安全学习:CSRF漏洞3

CSRF 漏洞学习网站&#xff1a;What is CSRF (Cross-site request forgery)? Tutorial & Examples | Web Security Academy CSRF Token 基本原理 CSRF Token 是服务端生成的唯一、随机且不可预测的字符串&#xff0c;用于验证客户端合法校验。 作用&#xff1a;防止攻击…

用 Nodemon 解决 npm run serve 频繁重启服务

Nodemon 是一个基于 Node.js 构建的开发工具&#xff0c;专为帮助开发者自动监控项目文件的更改而设计。每当文件发生变更时&#xff0c;Nodemon 会自动重启 Node.js 服务器&#xff0c;无需手动停止并重启。这对于提升开发速度、减少人工操作非常有帮助&#xff0c;尤其适用于…

django admin 中更新表数据 之后再将数据返回管理界面

在Django中&#xff0c;更新数据库中的数据并将其重新显示在Django Admin界面上通常涉及到几个步骤。这里我将详细说明如何在Django Admin中更新表数据&#xff0c;并确保更新后的数据能够立即在管理界面上显示。 定义模型 首先&#xff0c;确保你的模型&#xff08;Model&…

真.从“零”搞 VSCode+STM32CubeMx+C <1>构建

目录 前言 准备工作 创建STM32CubeMx项目 VSCode导入项目&配置 构建错误调试 后记 前言 去年10月开始接触单片机&#xff0c;一直在用树莓派的Pico&#xff0c;之前一直用Micropython&#xff0c;玩的不亦乐乎&#xff0c;试错阶段优势明显&#xff0c;很快就能鼓捣一…

C语言学习之结构体

在C语言中&#xff0c;我们已经学了好几种类型的数据。比如整型int、char、short等&#xff0c;浮点型double、float等。但是这些都是基本数据类型&#xff0c;而这些数据类型应用在实际编程里显然是不够用的。比如我们没有办法用一旦数据类型来定义一个”人“的属性。因此这里…

架构-计算机系统基础

计算机系统基础 一、计算机系统组成 &#xff08;一&#xff09;计算机系统层次结构 硬件组成 主机&#xff1a;包含CPU&#xff08;运算器控制器&#xff09;、主存储器&#xff08;内存&#xff09;。外设&#xff1a;输入设备、输出设备、辅助存储器&#xff08;外存&…

【计算机网络性能优化】从基础理论到实战调优

目录 前言技术背景与价值当前技术痛点解决方案概述目标读者说明 一、技术原理剖析核心概念图解核心作用讲解关键技术模块说明技术选型对比 二、实战演示环境配置要求核心代码实现案例1&#xff1a;iPerf3带宽测试案例2&#xff1a;TCP窗口优化案例3&#xff1a;QoS流量整形 运行…