如何从 Django 应用程序添加上下文处理器

发布于 2024-09-01 01:09:54 字数 258 浏览 1 评论 0原文

假设我正在编写一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

疑心病 2024-09-08 01:09:54

您认为应用程序可以直接添加到项目中而无需触及项目设置的假设是不正确的。

如果您将应用程序添加到项目中,您必须编辑设置,因为您必须将其添加到 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?

回梦 2024-09-08 01:09:54

上下文处理器非常有用,我不会太害羞地使用它们,但在某些情况下它没有意义。

当我需要在应用程序中的所有视图中包含一些简单的内容时,我会使用这种技术。我无法证明这是“正确”的做事方式,但它适用于我们的团队:

我将在文件顶部声明一个全局字典 template_vars 。每个视图都会将自己的变量添加到此字典中并将其传递给模板,并在 render_to_response 快捷方式中返回 template_vars

它看起来像这样:

template_vars = {
    'spam': 'eggs',
    }

def gallery(request):
    """
    portfolio gallery
    """

    template_vars['projects'] = Projects.objects.all()
    return render_to_response('portfolio/gallery.html', template_vars, context_instance=RequestContext(request))

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 returns template_vars in the render_to_response shortcut.

It looks something like this:

template_vars = {
    'spam': 'eggs',
    }

def gallery(request):
    """
    portfolio gallery
    """

    template_vars['projects'] = Projects.objects.all()
    return render_to_response('portfolio/gallery.html', template_vars, context_instance=RequestContext(request))
南烟 2024-09-08 01:09:54

是的,添加上下文处理器是实现此目的最推荐的方法。

Yeah, adding a context processor is the most recommended approach to achieve this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文