Django2,0-templates(1)-渲染模版方式和模版查詢路徑
阿新 • • 發佈:2018-12-19
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
-
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
-
模板查詢路徑
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資料夾
- 會先在