Rob*_*ley 2 python django django-templates
在我们的一个应用程序(运行Django 1.8)中,我们倾向于通过将字典传递到render()函数的context参数并将它们作为视图的一部分返回来呈现模板.例如:
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)
Run Code Online (Sandbox Code Playgroud)
现在我已经开始寻找它,我看到人们使用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)
Run Code Online (Sandbox Code Playgroud)
文档显示此Context对象可以以类似于字典(pop,copy,key assignment等)的方式进行交互,并且具有flatten()方法,可以将其与字典进行比较. https://docs.djangoproject.com/en/1.8/ref/templates/api/#playing-with-context.
我的问题是:我有没有理由想要使用Context对象而不是字典?我可以看到如果有人想要轻松访问请求变量,有人可能会发现RequestContext的子类很有用,但我想我错过了上下文对象的实用程序.
Python字典是已知键和变量值之间的映射.A Context()类似于字典,但是a Context()提供了额外的功能.
因此,在渲染模板时,您需要一个上下文.这可以是一个实例django.template.Context,但Django也有一个django.template.RequestContext稍微不同的子类.
该render()快捷方式创建RequestContext,除非它明确地传递不同的上下文实例.
[...]
RequestContext并且context processors是为了解决冗余问题而创建的.Context processors让您指定在每个上下文中自动设置的多个变量,而无需在每个render()调用中指定变量.
[...]
请记住,TEMPLATE_CONTEXT_PROCESSORS(在设置中)中的任何上下文处理器都将在该setteings文件提供的每个模板中可用.
自定义上下文处理器可以存在于代码库中的任何位置.所有Django关心的是您的自定义上下文处理器由context_processors您的TEMPLATES设置中的选项指向,或者您是否直接使用它的context_processors参数Engine.话虽如此,惯例是将它们保存在context_processors.py应用程序或项目中调用的文件中.
资料来源:掌握Django:核心.完整的Django 1.8LTS指南
更多信息:官方文档:RequestContext
| 归档时间: |
|
| 查看次数: |
2389 次 |
| 最近记录: |