Django教程 —— Django模板
引言
如何向请求者返回一个漂亮的页面呢? 肯定需要用到
html、css,如果想要更炫的效果还要加入js,问题来了,这么一堆字符串全都写到视图中,作为HttpResponse()的参数吗?
先看看如何拼接
html
# -*- coding:utf-8 -*-
@Author :Hui
@Desc :{book应用视图模块}
from django.views import View
from django.http import HttpResponse
# /book/index
def index(request):
"""图书首页"""
if request.method == "GET":
res_html = "<h1>GET请求 - 图书信息页</h1><br/>"
books = ["射雕英雄传", "神雕侠侣", "倚天屠龙记"]
res_html += "<ul>"
for book in books:
res_html += "<li>"
res_html += book
res_html += "</li>"
res_html += "</ul>"
return HttpResponse(res_html)
这样定义就太麻烦了吧,并且定义字符串是不会出任何效果和错误,如果有一个专门定义前端页面的地方就好了。
在
Django
中,将前端的内容定义在
模板
中,然后再把模板交给视图调用,各种漂亮、炫酷的效果就出现了。
运行环境
- Python 3.9
- Django 3.1.2
Django模板
创建模板
在
Django
项目下创建
templates
目录然后在创建
book
目录,代表这存放着
book
应用的模板文件。
目录结构如下图:
配置模板
在
Django
项目下的
setting.py
文件中找到
TEMPLATES
配置选项,配置如下目录路径
'DIRS': [BASE_DIR / 'templates']
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',
]
BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR
是你
Django
项目的绝对路径
可以在终端控制台输入如下命令
python manage.py shell
打开项目的
shell
终端进行调试。
定义模板
打开
templtes/book/index.html
文件,定义代码如下:
<!DOCTYPE html>
<html lang="zh-hans">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图书信息</title>
</head>
<h2>{{ title }}</h2>
{% for book in books %}
<li>{{ book.title }} --- {{ book.author }}</li>
{% endfor %}
</body>
</html>
在模板中输出变量语法如下,变量可能是从视图中传递过来的,也可能是在模板中定义的。
{{ 变量名 }}
在模板中编写代码段语法如下:
{% 代码段 %}
更多模板语法这里就不一一叙述了。
视图调用模板
调用模板分为三步骤:
- 找到模板
- 定义上下文
- 渲染模板
from django.views import View
from book.models import BookInfo
from django.template import loader
from django.http import HttpResponse
# /book/info
class InfoView(View):
"""图书信息视图类"""
def get(self, request):
# 从数据库中获取图书信息
books = BookInfo.objects.all()
# 获取模板
tmp = loader.get_template('book/index.html')
# 定义上下文
context = {
"title": "图书信息",
"books": books,
# 渲染模板
content = tmp.render(context)
return HttpResponse(content)
在浏览器上访问
http://127.0.0.1:8000/book/info
效果如下图
视图调用模板简写
视图调用模板都要执行以上三部分,于是
Django
提供了一个函数
render
封装了以上代码。
函数
render
包含3个参数:
-
第一个参数为
request对象 -
第二个参数为
模板文件路径 -
第三个参数为
字典,表示向模板中传递的上下文数据
调用
render
的代码如下:
from django.views import View
from book.models import BookInfo
from django.shortcuts import render
# /book/info
class InfoView(View):
"""图书信息视图类"""
def get(self, request):
# 从数据库中获取图书信息
books = BookInfo.objects.all()
# 定义上下文
context = {