如何从 Django 应用程序添加上下文处理器
假设我正在编写一个 Django 应用程序,并且该应用程序中的所有模板都需要某个变量。
据我所知,处理这个问题的“经典”方法是编写一个上下文处理器并将其添加到 settings.py 中的 TEMPLATE_CONTEXT_PROCESSORS 中。
我的问题是,考虑到应用程序应该“独立于”使用它们的实际项目,这是正确的方法吗?
换句话说,当将该应用程序部署到新项目时,有什么方法可以避免该项目必须明确地弄乱其设置?
Say I'm writing a Django app, and all the templates in the app require a certain variable.
The "classic" way to deal with this, afaik, is to write a context processor and add it to TEMPLATE_CONTEXT_PROCESSORS in the settings.py.
My question is, is this the right way to do it, considering that apps are supposed to be "independent" from the actual project using them?
In other words, when deploying that app to a new project, is there any way to avoid the project having to explicitly mess around with its settings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您认为应用程序可以直接添加到项目中而无需触及项目设置的假设是不正确的。
如果您将应用程序添加到项目中,您必须编辑设置,因为您必须将其添加到
INSTALLED_APPS
元组中。那么为什么不编辑上下文处理器列表呢?
Your assumption that apps can just be added in a project without touching the project's settings is not correct.
If you add an application to a project, you have to edit the settings, since you must add it in the
INSTALLED_APPS
tuple.So why not edit the context processor list?
上下文处理器非常有用,我不会太害羞地使用它们,但在某些情况下它没有意义。
当我需要在应用程序中的所有视图中包含一些简单的内容时,我会使用这种技术。我无法证明这是“正确”的做事方式,但它适用于我们的团队:
我将在文件顶部声明一个全局字典
template_vars
。每个视图都会将自己的变量添加到此字典中并将其传递给模板,并在render_to_response
快捷方式中返回template_vars
。它看起来像这样:
Context processors are very useful and I wouldn't be too shy in using them, but in some situations it doesn't make sense.
This is a technique I use when I need to include something simple to all views in an app. I cannot attest that this is the 'proper' way to do things, but it works for our team:
I'll declare a global dictionary
template_vars
at the top of the file. Every view would add its own variables to this dictionary and pass it to the template, and it returnstemplate_vars
in therender_to_response
shortcut.It looks something like this:
是的,添加上下文处理器是实现此目的最推荐的方法。
Yeah, adding a context processor is the most recommended approach to achieve this.