1、什么是Django模板
Django中内置了自己的模板系统,称为DTL(Django Template Language),Django模板语言。Django模板带有DTL语言的HTML文件,该文件可被Django编译,可以传递参数,实现数据动态变化,最终返回给客户端。
DTL中的语法涉及四个部分:
注释:注释;
变量:变量在模板被执行时将被替换为实际值 -- {{ ... }} ;
标签:用于控制模板逻辑 {% ... %} ;
过滤器:用于转换变量或标签的值。
2、相关配置
在setting.py中
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 指定模板文件存储的位置
'DIRS': [ BASE_DIR , 'templates'],
# 自动搜索应用目录
'APP_DIRS': True,
'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',
],
},
},
]
Django中有多个应用时,应优先在根目录templates中找,再到应用目录下找,不要重名。
3、渲染模板
在Django的模板系统中,可通过render()函数来完成渲染模板的功能。 其语法结构是:
from django.shortcuts import render
render(request,template_name,content=None,content_type=None,status=None)
request代表用于生成此响应的请求对象
template_name代表要渲染的模板文件的名称,一般放在templates目录下,需要自行创建
content代表要传递到模板的数据形成的数据字典
content_type代表模板文件的MIME类型,默认为text/html
status代表响应的状态码,默认为200
render()函数返回HttpResponse对象,是更加简洁的输出。
#显示界面,此仅仅是返回了一个界面,该界面在templates目录下,没有传递参数
def index(request):
return render(request,'index.html')
#有传递参数
def variable(request):
username = 'Tom'
age = 23
sex = True
score = {
'chinese':128,
'math':149,
'english':122
}
friends = ['John','Rose','Frank','Ben']
return render(request,'variable.html',locals())
视图函数variable(),通过locals()方法,以字典的方式,传递了视图函数中的所有变量,也可以单独设置一个字典来传递参数,如下说是:
#有传递参数
def variable(request):
username = 'Tom'
age = 23
sex = True
score = {
'chinese':128,
'math':149,
'english':122
}
friends = ['John','Rose','Frank','Ben']
return render(request,'variable.html',{"username":username,"age":age,"sex":sex,"score":score,"friends":friends})
或者:
#有传递参数
def variable(request):
username = 'Tom'
age = 23
sex = True
score = {
'chinese':128,
'math':149,
'english':122
}
friends = ['John','Rose','Frank','Ben']
context = {
"username":username,
"age":age,
"sex":sex,
"score":score,
"friends":friends
}
return render(request,'variable.html',context)
4、模板变量
模板变量,除了可以是字符串外,还可以是列表、字典和类对象。在DTL中的变量通过双花括号进行访问:
{{ variable}}
{{ variable.key }}
{{ variable.index }}
{{ variable.property }}
例子如下,view.py中的代码:
def variable(request):
username = 'Tom'
age = 23
sex = True
score = {
'chinese':128,
'math':149,
'english':122
}
friends = ['John','Rose','Frank','Ben']
return render(request,'variable.html',locals())
variable.html中的代码如下:
<body>
<h1>Variable</h1>
<p>username:{{ username }}</p>
<p>age:{{ age }}</p>
<p>sex:{{ sex }}</p>
<p>chinese:{{ score.chinese }}</p>
<p>math:{{ score.math }}</p>
<p>english:{{ score.english }}</p>
<p>{{ friends.0 }},{{ friends.1 }},{{ friends.2 }},{{ friends.3 }}</p>
{% include 'inc/footer.html'%}
</body>
别忘了在url.py中添加路由:
path('variable/',views.variable),
5、标签
5.1、for标签
<table width="900" cellpadding="10" celspacing="0" border="1">
<tr>
<td>id</td>
<td>name</td>
</tr>
{% for item in lists %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
{% empty %}
<tr>
<td colspan="2">对不起,列表为空</td>
</tr>
{% endfor %}
</table>
5.2、for循环中的内置变量
变量 | 描述 |
forloop.counter | 循环记数器,从1开始 |
forloop.counter0 | 循环记数器,从0开始 |
forloop.revcounter | 反向循环记数器,最后一个为1 |
forloop.revcounter0 | 反向循环记数器,最后一个为0 |
forloop.first | 当前循环为第一个时,该变量值为True |
forloop.last | 当前循环为最后一个时,该变量值为True |
def forloop(request):
books = [
{
'id':5,
'bookname': '孙子兵法大全集(超值金版)',
'price': 18.4,
'publishing': '新世界出版社',
'category': '历史'
},
{
'id': 11,
'bookname': '甲骨文丛书·拿破仑大帝(全2册) ',
'price': 119.5,
'publishing': '中信出版集团',
'category': '传记'
},
{
'id': 22,
'bookname': 'JavaScript DOM编程艺术(第2版)',
'price': 42.70,
'publishing': '人民邮电出版社',
'category': '计算机'
},
{
'id': 23,
'bookname': '精通iOS开发 第8版',
'price': 102.20,
'publishing': '人民邮电出版社',
'category': '计算机'
},
{
'id': 26,
'bookname': 'UNIX网络编程 卷1 套接字联网API(第3版)',
'price': 102.9,
'publishing': '人民邮电出版社',
'category': '计算机'
},
{
'id': 31,
'bookname': '曾国藩的正面与侧面:1+2(套装共两册)',
'price': 59.30,
'publishing': '岳麓书社',
'category': '传记'
},
{
'id': 40,
'bookname': '普京传:不可替代的俄罗斯硬汉 [Mr.Putin: Operative In The Kremlin] ',
'price': 39,
'publishing': '红旗出版社',
'category': '传记'
},
]
# lists = [
# {'id':5,'name':'Rose'},
# {'id': 7, 'name': 'Frank'},
# ]
lists = []
context = {
'books':books,
'lists':lists
}
return render(request,'forloop.html',context)
<table width="900" cellpadding="10" celspacing="0" border="1">
<tr>
<td>序号</td>
<td>书名</td>
<td>价格</td>
<td>出版社</td>
<td>分类</td>
<td>操作</td>
</tr>
{% for book in books %}
<tr class="{% cycle 'primary' 'second' %}">
<td>{{ forloop.counter }}</td>
<td>{{ book.bookname }}</td>
<td>{{ book.price }}</td>
<td>{{ book.publishing }}</td>
<td>{{ book.category }}</td>
<td>
<a href="/book/get/{{ book.id }}">修改</a>
<a href="/book/delete/{{ book.id }}">删除</a>
</td>
</tr>
{% endfor %}
</table>
还有urls.py中的路由:path('forloop/',views.forloop),
5.3、cycle循环结构
5.4、if结构
模板位 | 说明 |
openblock | {% |
closeblock | %} |
openvariable | {{ |
closevariable | }} |
opencomment | {# |
closecomment | #} |
5.5、verbatim结构
5.6、url语法
<p><a href="{% url 'deletebook' id=5 %}">删除5号图书</a></p>
5.7、 include
{% include 'inc/footer.html'%}
在inc文件夹下的footer.html中的全部代码如下:
<div style="text-align:center;font-size:14px;line-height:2em;">
<p>©达内教育版权所有 2002~2023</p>
<p>通讯地址:北京市中关村中鼎大厦7层</p>
<p>联系电话:010-123456789</p>
</div>
5.8 、csrf_token
<form action="" method="post">
{% csrf_token %}
<table width="800" align="center" border="1" cellpadding="10" cellspacing="0">
<tr>
<td>用户名</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>确认密码</td>
<td><input type="password" name="password2"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"></td>
</tr>
</table>
</form>