1.模板引擎和配置
常用引擎:DTL,Jinjia2
settings.py 文件中去配置
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
#backend为引擎可以替换
"DIRS": ["templates"],
#DIRS为模板路径
"APP_DIRS": True,
#APP_DIRS为true代表可以在应用中配置模板,但是需要在settings.py中找到
#INSTALLED_APPS = []将应用添加进去
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"app01",#添加的应用
]
2.模板中的变量
变量类型:数字,字符串,列表,元组,字典,集合,对象
示例:
(1)在templates文件夹下创建list.html文件
<body>
<h1>文章列表</h1>
<h2>作者:{{author}}</h2><!-- 一定是两个"{}" 且变量名要与py文件里面render函数传递的变量名相一致-->
<h2>发表文章的数量:{{number}}</h2>
<ul>
<li>文章内容:{{article_list.0}}</li><!--传递的是列表的话,不使用[],而是“.”,即使用"list_name.number"-->
<li>文章内容:{{article_list.1}}</li>
<li>文章内容:{{article_list.2}}</li>
</ul>
<p> {{info.name}}年龄{{info.age}}</p>
<p>喜欢的编程语言:{{info.programming_language.0}}</p>
</body>
(2)在views.pu文件下创建函数
from django.shortcuts import render
def list(request):
author="andy" #字符串
article_number=20 #数字
article_list=["第一篇文章:什么是django", #列表
"第二篇文章:django的mvt模式",
"第三篇文章:django的视图"]
info={ #字典
'name':'hk',
'age':19,
'programming_language':['python','html','c++',"javascipt"]
}
return render(request,"list.html",
{
'author':author,
'number':article_number, #在html文件中number是变量,但在这里的py文件里面,article_number是变量
'article_list':article_list,
'info':info
}) #第一个参数必不可少为request,第二个是对应的html文件名,第三个是模板变量名
(3)在urls.py里加入路径即函数
from . import views
urlpatterns = [
path("list/",views.list)
]
效果图:

3.模板标签
常用模板标签:
- 循环控制
- 条件控制
- 模板注释
- url解析
- with语句块
- 时间显示
- 继承与包含
循环控制:for标签
循环列表或元组:
{% for item in data_list%}<!--注意这里面是{% %},不是{{}}-->
<li>内容</li><!--在里面就可以放item,从列表第一个开始-->
{%empty%} <!--当列表不存在的时候输出下面的暂无内容-->
<li>暂无内容</li>
{%endfor%}
循环字典:
{% for key,value in data.items%}<!--要有.items-->
<p>{{key}}:{{value}}</p><!--{{key}}->{{value}}-->
{%empty%} <!--当字典不存在的时候输出下面的暂无内容-->
<li>暂无内容</li>
{%endfor%}
重复循环:
{%cycle 'row1'''row2%}<!--通常用于隔行换色-->
示例:
<head>
<style>
.row1{
color: #05b4ff;
}
.row2{
color:red;
}
</style>
</head>
{%for article in article_list%}
<ul>
<li class="{%cycle 'row1' 'row2'%}">{{article}}</li>
</ul>
{% empty %}
<li>暂无内容</li>
{% endfor %}
{% for key,value in info.items %}
<p>{{key}}:{{value}}</p>
{%empty%}
<p>暂无内容</p>
{%endfor%}

循环内的变量:在循环内部使用
{forloop.first} | 如果是第一次迭代,为True |
{{forloop.last}} | 如果是最后一次迭代,为True |
{{forloop.counter}} | 计数器,从0开始 |
{{forloop.counter}} | 计数器,从1开始 |
条件控制:if标签
{% if %}
{%elif%}
{%else%}
{%endif%}
示例:
{%for article in article_list%}
<ul>
<li class="{%cycle 'row1' 'row2'%}">{{article}}</li>
{%if forloop.counter == 1%}
置顶
{%endif%}
</ul>
{% empty %}
{% for key,value in info.items %}
<p>{{key}}:{{value}}</p>
{%empty%}
<p>暂无内容</p>
{%endfor%}
{% if info.age < 18 %} <!--"<"前后都有一个" "-->
<p>未成年</p>
{%elif 18 <= info.age and info.age <= 25 %}
<p> 青年才俊</p>
{%else%}
<p>潜力股</p>
{%endif%}

4.模板过滤器
基础语法:
{{value|filter_name:params}}
常用的过滤器:
upper urlencode length default floatformat safe random truncatechars
示例:
upper:转换为大写
<h2>作者:{{author|upper}}</h2>
default:设置默认值
<h2>发表文章的数量:{{number}} 性别:{{gender|default:'未知'}}</h2>
truncatechars:字符截断
<li class="{%cycle 'row1' 'row2'%}">{{article|truncatechars:10}}</li>
random:随机选择列表元素
<p>喜欢的编程语言:{{info.programming_language|random}}</p>
safe:不需要进行 HTML 转义处理
# views.py
from django.shortcuts import render
def my_view(request):
html_content = '<h1>Hello, <em>world</em>!</h1>'
return render(request, 'my_template.html', {'html_content': html_content})
<!-- my_template.html -->
<!DOCTYPE html>
<html>
<head>
<title>Safe Filter Example</title>
</head>
<body>
<div>
{{ html_content|safe }}
</div>
</body>
</html>
5.模板继承和包含
继承:{% extends %}
{% extends 'template_name.html' %}
例如,如果你有一个名为base.html的基础模板,你可以创建一个child.html模板,它通过{% extends "base.html" %}来继承基础模板。
在基础模板中,你可以使用{% block %}标签来定义可被子模板重写的区域。例如:
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
然后,在子模板中,你可以重写这些区域:
<!-- child.html -->
{% extends "base.html" %}
{% block title %}My Child Page{% endblock %}
{% block content %}
<p>This is the content of the child page.</p>
{% endblock %}
当Django渲染child.html时,它会首先查找base.html,然后用child.html中定义的块内容替换base.html中相应的块。
还有一个注意事项:当你子模板使用继承后,增添内容必须都在{%block xx%}和{%endblock %}之间,否则不会显示增添的内容
包含(引入):{%include%}
{% include 'template_name.html' %}
首先,我们创建一个包含导航栏内容的 navbar.html
文件:
<nav>
<a href="/">首页</a>
<a href="/about">关于我们</a>
<a href="/contact">联系我们</a>
</nav>
然后,在我们的页面模板中使用 “include” 标签来包含导航栏模板:
{% include 'navbar.html' %}
<h1>欢迎来到首页</h1>
<p>这是我们的网站首页的内容。</p>