【发布时间】:2017-11-23 06:28:55
【问题描述】:
在我们的一个应用程序(运行 Django 1.8)中,我们倾向于通过将字典传递给 render() 函数的上下文参数并将它们作为视图的一部分返回来呈现模板。例如:
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)
文档显示此 Context 对象可以通过类似于字典的方式(弹出、复制、键分配等)进行交互,并且有一个 flatten() 方法可以让您将其与字典进行比较。 https://docs.djangoproject.com/en/1.8/ref/templates/api/#playing-with-context。
我的问题是:我有什么理由想要使用 Context 对象而不是字典?如果有人想要轻松访问请求变量,我可以看到他们可能会发现 RequestContext 的子类很有用,但我认为我缺少上下文对象的实用程序。
【问题讨论】:
标签: python django django-templates