Python全系列 教程
3567个小节阅读:5929.4k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
作为一个Web框架,Django需要一种方便的方式来动态生成HTML。最常用的方法依赖于模板。模板包含所需HTML输出的静态部分以及描述如何插入动态内容的特殊语法
在settings中配置:
xxxxxxxxxx
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
]
django.template.loader.get_template
该函数使用给定名称加载模板并返回一个 Template对象,找到第一个匹配的模板即返回
xxxxxxxxxx
template = get_template('story_detail.html')
Django将要查找的文件,依次为:
xxxxxxxxxx
from django.shortcuts import render
def my_view(request):
return render(
request,
'myapp/index.html',
{'foo': 'bar'},
content_type='application/xhtml+xml'
)
xxxxxxxxxx
from django.http import HttpResponse
from django.template import loader
def my_view(request):
t = loader.get_template('myapp/index.html')
c = {'foo': 'bar'}
return HttpResponse(t.render(c, request), content_type='application/xhtml+xml')
django.template.loader.select_template
select_template() 用法类似 get_template() ,除了它需要一个模板名称的列表。它按顺序尝试每个名称并返回存在的第一个模板
xxxxxxxxxx
template = select_template(['story_253_detail.html','story_detail.html'])
Django将要查找的文件,依次为:
实时效果反馈
1. 关于Django模板,基本规则说法错误的是?
A 返回模板可以使用render函数返回模板
B 返回模板的引擎可以使用内置和3方引擎
C 模板的查找按路径优先级按顺序查找
D 模板的名称不能重复,不然会报错
答案
1=>D