templates
- Django自带的是DTL(Django Templates language)
- DTL模版是一种带有特殊语法的HTML文件。
- 该文件可以被Django编译
- 可以传递参数进去
- 实现数据动态化
- 编译完成后,生成一个普通的HTML文件
- DTL模版是一种带有特殊语法的HTML文件。
渲染模版方式
-
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("page.html") return HttpResponse(html)
-
render()
直接将模板渲染称字符串和包装成HttpResponse
对象一步到位完成。推荐该方法from django.shortcuts import render from django.http import HttpResponse def return_page(request): return render(request, "page.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
中查找
- 如果为False,就只在
-
模板查找顺序
- 会先在
DIRS
这个列表中一次找到路径下有无该模板,如果有,则返回 - 如果没有,则检查当前视图函数所处的app是否已经安装,如果已经安装,则就先该app下的templates文件夹中查找模板
- 如果没有,则检查其他已经安装的app下的templates文件夹
- 如果没有,则抛出
TemplateDoesNotExist
的异常
- 优先级
DIRS
>本app的templates文件夹
>其他app的templates文件夹
- 会先在