在我們的應用程序之一(運行Django 1.8)中,我們傾向於通過將字典傳遞給render()函數的上下文參數來呈現模板,並將它們作爲視圖的一部分返回。例如:Django模板上下文對象的用途?
from django.views.generic import View
class HomePageView(View):
def get(self, request, *args, **kwargs):
context = {'foo': 'bar', 'foo2': 'bar2'}
return render(request, "page.html", context)
現在,我已經開始尋找它,我看到的使用Django「上下文」對象,而不是字典人們的例證。
from django.views.generic import View
from django.template import Context
class HomePageView(View):
def get(self, request, *args, **kwargs):
context = Context()
context['foo'] = 'bar'
context['foo2'] = 'bar2'
return render(request, "page.html", context)
文檔顯示,該上下文對象可以以類似於字典(POP,複製,密鑰分配等)的方式進行交互,並且具有扁平化()方法,可以讓你把它比作一本字典。 https://docs.djangoproject.com/en/1.8/ref/templates/api/#playing-with-context。
我的問題是:我有沒有任何理由要使用Context對象而不是字典?我可以看到有人可能會發現RequestContext的子類有用,如果他們想要容易訪問請求變量,但我認爲我缺少上下文對象的實用程序。
唉唉我已經錯過了有關模板如何需要上下文對象,而是傳遞一個字典到渲染功能* *實例化一個RequestContext對象,如文檔中的行一條捷徑。很高興知道,謝謝! –