打開current_datetime 視圖。 以下是其內容:
from django.http import HttpResponseimport datetimedef current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % 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("<html><body>It is now {{ current_date }}.</body></html>") 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)然而,基于以下幾個原因,該方法還算不上簡潔:
新聞熱點
疑難解答
圖片精選