1. 程式人生 > >Django2,0-templates(1)-渲染模版方式和模版查詢路徑

Django2,0-templates(1)-渲染模版方式和模版查詢路徑

templates

  • Django自帶的是DTL(Django Templates language)
    • DTL模版是一種帶有特殊語法的HTML檔案。
      • 該檔案可以被Django編譯
      • 可以傳遞引數進去
      • 實現資料動態化
    • 編譯完成後,生成一個普通的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("page.html") return HttpResponse(html)
  2. render()直接將模板渲染稱字串和包裝成HttpResponse物件一步到位完成。推薦該方法

    from django.shortcuts import render
    from django.http import HttpResponse
    
    def return_page(request):
        return render(request, "page.html"
    )
  3. 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中查詢
  • 模板查詢順序

    1. 會先在DIRS這個列表中一次找到路徑下有無該模板,如果有,則返回
    2. 如果沒有,則檢查當前檢視函式所處的app是否已經安裝,如果已經安裝,則就先該app下的templates資料夾中查詢模板
    3. 如果沒有,則檢查其他已經安裝的app下的templates資料夾
    4. 如果沒有,則丟擲TemplateDoesNotExist的異常
    • 優先順序DIRS>本app的templates資料夾>其他app的templates資料夾