Django - 在模板之前访问上下文字典
我希望在实际渲染之前使用上下文处理器或中间件来修改传递给 render_to_response 的字典的值。我有一个正在尝试实现的消息传递模式,该模式将根据我想要在呈现模板之前搜索上下文的用户类型的存在来填充消息列表。
示例:
def myview(...):
...
return render_to_response('template.html',
{'variable': variable},
)
我希望能够向上下文中添加有关“变量”存在的附加信息。
在我的视图定义“变量”之后但在它到达模板之前,如何访问“变量”,以便我可以进一步修改上下文?
I'm hoping to use a context processor or middleware to modify the values of the dictionary passed to render_to_response prior to the actual rendering. I have a messaging schema I'm trying to implement that would populate a message list based on the existence of a type of user that I'd like to search the context for prior to the rendering of the template.
Example:
def myview(...):
...
return render_to_response('template.html',
{'variable': variable},
)
and I'd like to be able to add additional information to the context on the existence of 'variable'.
How can I access 'variable' after my view defines it but before it gets to the template so that I can further modify the context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 TemplateResponse:
use TemplateResponse:
这很容易。如果您在示例中只提供了一点点代码,那么答案可能会让您感到困惑。
评论更新:
render_to_response()
的结果是一个 HTTPResponse 对象,其中包含针对 Context 呈现的模板。 (据我所知)该对象没有与之关联的上下文。我想您可以将 render_to_response() 的结果保存在变量中,然后访问您传递给它的上下文,但我不确定您要解决什么问题。您在渲染期间修改了上下文吗?如果是这样,您可能会发现该信息不再存在,因为上下文有一个范围堆栈,该堆栈在模板处理期间被推送/弹出。
This is easy. If you have supplied just a little bit more code in your example the answer might have bit you.
Update to comment:
The result of a
render_to_response()
is an HTTPResponse object containing a template rendered against a Context. That object does not (to my knowledge) have a context associated with it. I suppose you could save the result ofrender_to_response()
in a variable and then access the Context you passed it, but I'm not sure what problem you are trying to solve.Did you modify the Context during rendering? If so you may find that the information is not there any longer because the Context has a scope stack which is pushed/popped during template processing.
您可以为上下文创建一个字典:
也许 RequestContext 是您正在寻找的东西。
You can create a dictonary for the context:
Maybe the RequestContext is the thing you are looking for.