templates
Django自带的是DTL(Django Templates language)
DTL模版是一种带有特殊语法的HTML文件。
渲染模版方式有两种
方式1:
render_to_string()找到模版,然后将模版编译后渲染成Python的字符串格式。
最后再通过HttpResource类包装成一个HttpResponse对象返回
from django.template.loader import render_to_string
from django.http import HttpResponse
def return_page(request):
html = render_to_string("login.html")
return HttpResponse(html)
方式2:
render()直接将模板渲染称字符串和包装成HttpResponse对象一步到位完成。
from django.shortcuts import render
from django.http import HttpResponse
def return_page(request):
return render(request, "login.html")
render_to_response将被render取代,功能一致
模版查找路径
在setting.py中查看
# 该配置包含了模板引擎的配置、模板查找路径的配置、模板上下文的配置等。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')] #自定义templates文件夹的绝对路径
,
'APP_DIRS': True, # 注意 开启App内查找templates文件夹下的html
'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',
],
},
},
]
模板查找路径
DIRS:一个列表,存放所有的模板路径。
APP_DIRS :默认为True,为True时,会在INSTALLED_APP已安装的APP下的
templates文件夹(注意文件夹名一定是templates)中查找模板
如果为False,就只在DIRS中查找
模板查找顺序
会先在DIRS这个列表中一次找到路径下有无该模板,如果有,则返回
如果