Django架構下在視圖中使用模版的方法

來源:互聯網
上載者:User
開啟current_datetime 視圖。 以下是其內容:

from django.http import HttpResponseimport datetimedef current_datetime(request):  now = datetime.datetime.now()  html = "It is now %s." % now  return HttpResponse(html)

讓我們用 Django 模板系統來修改該視圖。 第一步,你可能已經想到了要做下面這樣的修改:

from django.template import Template, Contextfrom django.http import HttpResponseimport datetimedef current_datetime(request):  now = datetime.datetime.now()  t = Template("It is now {{ current_date }}.")  html = t.render(Context({'current_date': now}))  return HttpResponse(html)

沒錯,它確實使用了模板系統,但是並沒有解決我們在本章開頭所指出的問題。 也就是說,模板仍然嵌入在Python代碼裡,並未真正的實現資料與表現的分離。 讓我們將模板置於一個 單獨的檔案 中,並且讓視圖載入該檔案來解決此問題。

你可能首先考慮把模板儲存在檔案系統的某個位置並用 Python 內建的檔案操作函數來讀取檔案內容。 假設檔案儲存在 /home/djangouser/templates/mytemplate.html 中的話,代碼就會像下面這樣:

from django.template import Template, Contextfrom django.http import HttpResponseimport datetimedef current_datetime(request):  now = datetime.datetime.now()  # Simple way of using templates from the filesystem.  # This is BAD because it doesn't account for missing files!  fp = open('/home/djangouser/templates/mytemplate.html')  t = Template(fp.read())  fp.close()  html = t.render(Context({'current_date': now}))  return HttpResponse(html)

然而,基於以下幾個原因,該方法還算不上簡潔:

  • 它沒有對檔案丟失的情況做出處理。 如果檔案 mytemplate.html 不存在或者不可讀, open() 函數調用將會引發 IOError 異常。
  • 這裡對模板檔案的位置進行了寫入程式碼。 如果你在每個視圖函數都用該技術,就要不斷複製這些模板的位置。 更不用說還要帶來大量的輸入工作!
  • 它包含了大量令人生厭的重複代碼。 與其在每次載入模板時都調用 open() 、 fp.read() 和 fp.close() ,還不如做出更佳選擇。
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.