開啟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() ,還不如做出更佳選擇。