Python全系列 教程
3567个小节阅读:5930k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
作为一个Web框架,Django需要一种方便的方式来动态生成HTML。最常用的方法依赖于模板。模板包含所需HTML输出的静态部分以及描述如何插入动态内容的特殊语法。
对模板引擎的一般支持和Django模板语言的实现都存在于 django.template 命名空间中
在settings中配置:
x# 配置模板
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
],
},
},
]
笔记:
假如settings中配置如下:
xxxxxxxxxx
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'/home/html/example.com',
'/home/html/default',
],
},
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [
'/home/html/jinja2',
],
},
]
get_template
该函数使用给定名称加载模板并返回一个 Template对象,找到第一个匹配的模板即返回
xxxxxxxxxx
template = get_template('story_detail.html')
Django将要查找的文件,依次为:
示例:
xxxxxxxxxx
# 最常用的render
from django.shortcuts import render
def my_view(request):
# View code here...
return render(request, 'myapp/index.html', {
'foo': 'bar',
}, content_type='application/xhtml+xml')
# 相当于基础的get_template:
from django.http import HttpResponse
from django.template import loader
def my_view(request):
# View code here...
template = loader.get_template('myapp/index.html')
context = {'foo': 'bar'}
# 注意,这个 render 和 快捷键 render 不是一个对象
return HttpResponse(template.render(context, request), content_type='application/xhtml+xml')
select_template
select_template() 用法类似 get_template() ,除了它需要一个模板名称的列表。它按顺序尝试每个名称并返回存在的第一个模板
xxxxxxxxxx
template = select_template(['story_253_detail.html','story_detail.html'])
Django将要查找的文件,依次为: