Django模板(二)
(上接 Django基本概念入门)
模板是用来生成HTML页面的。
一、基础语法
| 功能 | 语法/示例 | 说明 |
|---|---|---|
| 变量渲染 | {{ 变量名 }} | 动态显示数据 |
| 逻辑控制 | {% if %}, {% for %} |
条件/循环渲染 |
| 模板继承 | {% extends %}, {% block %} | 避免重复 HTML 结构 |
| 静态文件 | {% static 'path' %} | 加载 CSS/JS/图片 |
| 自定义过滤器 | @register.filter | 扩展模板功能 |
二、案例
在项目文件夹下创建 templetes 文件夹,并在文件夹下创建 welcome.html文件
案例描述:将 "你好 django!" 这段文字渲染到页面
基本步骤:
-
在创建 html 模板
-
修改 settings.py 定义模板路径
-
在 views.py 中将 "你好 django!" 提交到创建的html 页面
-
修改 urls.py 定义路由
目录如下
tex
djangoProject/ -- 项目根目录
├── manage.py -- 项目管理命令行工具,项目的总指挥,通过它来执行
各种 Django 命令
└── djangoProject/ -- 项目容器目录(与项目同名)
├── __init__.py -- Python 包声明文件
├── settings.py -- 项目的核心配置文件
....
├── templetes
└── welcome.html
在 welcome.html 文件中做如下编辑
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{ welcome }}</h1>
</body>
</html>
修改项目的 settings.py 文件,说明模板文件路径
python
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'] # 此处需要修改为模板路径
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
修改 view.py 向模板文件提交数据
python
from django.shortcuts import render
def welcome(request):
context = {}
context['welcome'] = '你好 django!'
return render(request, 'welcome.html', context)
修改 urls.py 配置路由
python
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('index/', views.welcome, name='welcome'),
]
运行项目访问如下链接
url
http://localhost:8000/index/
三、标签取值
上一章节的案例演示了如何获取字符串中的值,其实也可以在模板的 html 中获取列表和字典的值。取值案如下
| views.py中的传值 | 模板html页面取值 | 页面显示 | |
|---|---|---|---|
| list | context['welcome'] =['value1','value2','value3'] | {{ welcome.0 }} | value1 |
| dict | context['welcome'] ={'name':'zhang san','age':'1'} | {{ welcome.name }} | zhang san |
3.1 管道
管道,就是对结果进行加工。格式为 a|b|c (支持对此加工,将结果a,先经过b加工,加工后的结果再进行c加工)。
其实也可以在view层直接加工得到想要的结果,管道适用于将同一结果进行多元化展现。
| 管道说明 | views.py中的传值 | 模板html页面取值 | 页面显示 |
|---|---|---|---|
| 过滤器支持嵌套使用 | context['welcome'] =['value1','value2','value3'] | {{ welcome|first|upper }} | VALUE1 |
| 提供默认值 | context['welcome'] =None | {{ welcome|default:"6" }} | 6 |
| 返回结果长度 | context['welcome'] ='abcd' | {{ welcome|length }} | 4 |
| 文件大小 | context['welcome'] =1024 | {{ welcome|filesizeformat }} | 1.0K |
| 日期格式化 | context['welcome'] =now | {{ welcome|date:'Y-m-d'}} | 2026-04-07 |
| 安全应用 | context['welcome'] = "< a href='https://www.baidu.com/'>百度一下" | {{ welcome|safe }} | 百度的超链接(不做转换,返回的是字符串) |
- 截断操作
| 管道说明 | views.py中的传值 | 模板html页面取值 | 页面显示 |
|---|---|---|---|
| 带有参数管道 | context['welcome'] ='you are my hero' | {{ welcome|truncatewords:"3" }} | you are my... |
| 字符串截断 | context['welcome'] ='you are my hero' | {{ welcome|truncatechars:"3" }} | yo... |
- 基本语法
| 管道说明 | views.py中的传值 | 模板html页面取值 | 页面显示 |
|---|---|---|---|
| if...else... | context['welcome'] =1 | {%if welcome == 1%}张三{%else%}李四{%endif%} | 张三 |
| for | context['welcome'] =['value1','value2','value3'] | {% for i in welcome %} {{ i }} {% endfor %} | value1value2value3 |
| 注释 | {#写了一行注释#} | ||
| 引入其他页面 | {% include "test.html" %} |
-
跨站请求伪造(CSRF)攻击
CSRF攻击是一种网络安全漏洞,攻击者诱导用户在已登录的网站(如银行、邮箱等)上执行非本意的操作,如转账、修改密码等。这种攻击利用了网站对用户浏览器的信任。
标签为 {% csrf_token %}
html<form method="post" action="/submit-form/"> {% csrf_token %} <input type="text" name="username" placeholder="用户名"> <input type="password" name="password" placeholder="密码"> <button type="submit">提交</button> </form>如上为一个登录的表单页面,Djanjo会为没一个表单生成一个token,渲染带有{% csrf_token %}的页面吗,这个表单会和token一同下发,用户提交表单的时候会连同token一同进行校验。校验通过则正常,不通过则返回403错误。
四、自定义标签和过滤器
-
在templetes文件夹同级目录创建文件夹templatetags
-
在 templatetags 目录下创建任意 py 文件(文件名可以自定义,如 fisrt_tag.py)
pythonfrom django import template # register的名字是固定的 register = template.Library() 自定义过滤器 @register.filter(name='add') def add_tag(a, b): return a + b # 自定义标签 @register.simple_tag(name='max') def max_tag(a, b): if a > b: return a else: return b -
修改settings.py添加配置项 libraries
python
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
"libraries": {
'first_tags': 'templatetags.first_tags'
}
},
},
]
-
页面调用
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% load first_tags %} <h1>{{ 5|add:2 }}</h1> <h1>{% max 5 2 %}</h1> </body> </html>
五、模板继承
模板可以用继承的方式来实现复用,减少冗余。
-
在templetes目录下创建base.html文件
html<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>父模块</title> </head> <body> <h1>base templete</h1> {% block mainbody %} 留给子模块添加内容 {% endblock %} </body> </html>其中block部分是父模块的预留区域,留给子模块添加内容,mainbody 为预留区域的名称。
-
在子模块中引用父模块
在templetes目录下创建other.html文件
html{%extends "base.html" %} {% block mainbody %} <p>我的个性化部分</p> {% endblock %} -
python
from django.http import HttpResponse from django.shortcuts import render def welcome(request): context = {} return render(request, 'other.html')
python
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('other/', views.welcome, name='other'),
]
-
访问如下链接
urlhttp://localhost:8000/other/结果如下
texbase templete 我的个性化部分