Django:渲染快捷方式函数中context_instance参数的用法是什么? [英] Django: What's the use of the context_instance parameter in the render shortcut function?
问题描述
根据上面的链接, context_instance 参数定义为
上下文用于渲染模板的实例。默认情况下,模板将使用RequestContext实例呈现(填充请求和字典中的值)。
,我没有看到可以从提供context_instance参数中获益的任何方案。我的意思是,如果我需要提供额外的上下文值,我将它们添加到字典参数。我不知道context_instance如何有用。请教育我谢谢。
主要场景是使某些变量在模板中可用。例如, auth
上下文处理器使(其中包括)可用于模板中的用户
变量,以便您不必自己通过。虽然这是一个很大的段落,但 Django文档一个简单的说,通过添加 context_instance = RequestContext(request)
到 render
调用,您的 settings.py
中定义的所有处理器( TEMPLATE_CONTEXT_PROCESSORS
变量)按顺序执行。这些处理器中的每一个返回一个 dict
,其中包含在模板中可用的变量。使用默认设置,这意味着您不必添加例如用户
, csrf
或消息
变量自己:这是由处理器完成。
自己的上下文处理器的一个例子是将你的主菜单参数添加到模板中。假设您想要突出显示用户正在查看的当前类别的菜单:通过创建自己的上下文处理器来确定当前位置,它可以在模板中添加一些变量,这些变量用于您的菜单进行突出显示。
Documentation on 'Render' shortcut
According to the link above, the context_instance parameter is defined as
The context instance to render the template with. By default, the template will be rendered with a RequestContext instance (filled with values from request and dictionary).
With this definition in mind, I don't see any scenarios that would benefit from supplying the context_instance argument. I mean if I need to provide additional context values I would just add them to the dictionary parameter. I don't know how context_instance can be useful. Please educate me. Thanks.
The main scenario is to make certain variables available in your template. For example, the auth
context processor makes (amongst others) the user
variable available for use in your template so that you don't have to pass it yourself. Although it's quite a big paragraph, the Django documentation does quite a good job at explaining it.
In a nutshell: by adding context_instance=RequestContext(request)
to your render
call, all processors defined in your settings.py
(under the TEMPLATE_CONTEXT_PROCESSORS
variable) are executed in order. Each of these processors return a dict
with variables that are made available in the template. Using the default set, this means you do not have to add e.g. the user
, csrf
or messages
variables yourself: this is done by the processors.
An example for own context processor would be to add your main menu parameters to the template. Say you want to highlight the menu for the current category the user is viewing: by creating your own context processor that determines the current location, it could add some variables in the template that are used by your menu to do the highlighting.
这篇关于Django:渲染快捷方式函数中context_instance参数的用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!