知识点:
- 路径配置
- 渲染方式
- 模板变量
前面的两节中我们都是用简单的 django.http.HttpResponse 来把内容显示到网页上,本节将讲解如何使用渲染模板的方法来显示内容。
作为Web 框架,Django 需要一种很便利的方法以动态地生成HTML。 最常见的做法是使用模板。模板包含所需HTML 输出的静态部分,以及一些特殊的语法,描述如何将动态内容插入。
1.路径配置
在配置文件setting.py中找到TEMPLATES设置来配置。
这是一个设置选项的列表,模板大都包含两项通用设置;
DIRS 定义一个目录列表,模板引擎按列表顺序搜索这些目录以查找模板源文件。
APP_DIRS告诉模板引擎是否应该进入每个已安装的应用中查找模板。
通常用法:在app下面创建template目录,将模版文件,放在包含模版的目录的template子目录下。 将setting文件中INSTALLED_APPS 这个列表中添加对应的app名字。
基本思路是,使得每个APP的的模版子目录下都有一个子目录来唯一对应这个APP。
当APP_DIRS值为True,则模板会去安装了的app下面的templates文件夹查找模板。
我们之前创建了books的app,将这个app添加到setting.py文件的INSTALLED_APPS列表中:
# setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'books',
]
2.常用的模板渲染方法。
我们刚开始是原始的直接将html字符串硬编码HttpResponse中。
def index(request):
return HttpResponse('Hello Django World!')
使用template和Context动态修改html中的内容来构建。
#第一种
from django.template import Template,Context
def index_1(request,bn):
# 生成模板作用
t = Template('这是首页,欢迎浏览{{books_name}}')
# 生成上下文
c = Context({'books_name':bn})
# 渲染
html = t.render(c)
# 响应
return HttpResponse(html)
django.template.loader 定义了函数以加载模板。
get_template(template_name,using = None)
该函数使用给定的名称加载模板并返回一个Template 对象.get_template()尝试获取每个模板直到有一个成功满足。
如果需要接收多个模板对象,则也提供了select_template的函数,这个函数和get_template()很相似, 只不过它用了一个模板名称的列表作为参数。 按顺序搜索模板名称列表内的模板并返回第一个存在的模板
如果模板不能成功找到,将会抛出TemplateDoesNotExist。 如果能够找到模板但是包含非法值,将会抛出TemplateSyntaxError。
#第二种
from django.template.loader import get_template
def index_2(request,bn):
t = get_template('books/index.html')
html = t.render({'books_name':bn})
return HttpResponse(html)
为了减少加载模板、渲染模板等重复工作,django提供了处理这些工作的快捷函数。
render_to_string(template_name, context=None, request=None,using=None)
#第三种
from django.template.loader import render_to_string
def index_3(request,bn):
html = render_to_string('books/index.html',
{'books_name':bn})
return HttpResponse(html)
使用render_to_response进行渲染,不需要HttpResponse。
#第四种
from django.shortcuts import render_to_response
def index_4(request,bn):
return render_to_response('books/index.html',
{'books_name': bn})
使用render进行渲染。
# 第五种
from django.shortcuts import render
def index_5(request,bn):
return render(request,'books/index.html',
{'books_name': bn})
3.模板变量
1、语法:{{变量名}}
2、命名由字母和数字以及下划线组成,不能有空格和标点符号。
3、可以使用字典、模型、方法、函数、列表。
4、不要和python或django关键字重名。
原因:如果data是一个字典,那么访问data.items将会访问data这个字典的key名为items的值,而不会访问字典的items方法。
5.变量和查找
点在模板渲染时有特殊的含义。 变量名中点表示查找。 具体一点,当模板系统遇到变量名中的一个点时,它会按下面的顺序进行查找:字典查找,属性查找,列表索引查找。
模板变量的例子:
{# books/templates/books/index.html #}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
这个变量是字符串对象:{{ books_name}}<br>
这个变量是函数对象:{{ hello}}<br>
这个变量是类方法对象:{{ fruits_say}}<br>
这个变量是类对象:{{ fruits}}<br>
这个变量是类对象,访问类对象的属性:{{ fruits.name}}<br>
这个变量是类对象,访问类对象的方法:{{ fruits.say}}<br>
这个变量是列表对象{{ list }}<br>
这个变量是列表对象,访问列表的元素{{ list.1 }}<br>
这个变量是字典对象{{ dict }}<br>
这个变量是字典对象,访问字典的键{{ dict.a }}<br>
</body>
</html>
# books/views.py
def hello():
return 'django'
class Fruits:
def __init__(self, name, color):
self.name = name
self.color = color
def say(self):
return 'HAHAHAHA'
ap = Fruits('apple','red')
ls = ['x','y','z']
dc = {'a':1,'b':2}
from django.shortcuts import render
def index_5(request,bn):
return render(request,'books/index.html',
context={'books_name':'python',#字符串
'hello':hello, # 函数
'fruits_say':ap.say, # 方法
'fruits':ap, # 类对象
'list':ls, # 列表
'dict':dc, # 字典
})
网友评论