這篇文章主要介紹了Django框架下在視圖中使用模版的方法,Django是Python豐富多彩的眾框架中最有人氣的一個,需要的朋友可以參考下
打開current_datetime 視圖。 以下是其內容:
- from django.http import HttpResponse
- import datetime
- def 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, Context
- from django.http import HttpResponse
- import datetime
- def 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, Context
- from django.http import HttpResponse
- import datetime
- def 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() ,還不如做出更佳選擇。
新聞熱點
疑難解答