Django - 设置和使用 site-wide 变量以在模板中使用

Django - Set and use site-wide variables for use in templates

我正在寻找一种方法来设置一些 site-wide(或 app-wide)变量,例如我将在模板中使用的网站(或应用程序)标题(例如在我的 header 中)。我想到了 WordPress 的 bloginfo()

理想情况下,我希望能够在站点或应用程序级别定义任何类型的属性。例如,对于给定的应用程序,我有:

应用程序

--属性1(如标题)

--属性2(例如联系邮箱)

--型号1

----属性X

----属性Y

----...

意味着 "attribute1" 对我的应用来说是独一无二的。然后我需要一种方法来在我的模板中使用 attribute1 的值。 我希望我的问题很清楚。

如果您希望在模板中使用这些变量,那么您应该查看 context processors。最简单的解决方案是将 context_processors.py 添加到您的应用程序或项目,然后将此文件的路径添加到设置中的上下文处理器列表中

我一直使用站点范围(或应用程序范围)的变量 context processors

在您的应用程序中创建一个名为 context_processors.py 的单独文件(不用说,这样命名不是强制性的,这只是为了约定)并且该文件必须至少定义一个函数,该函数接受request 参数和 returns 字典。

类似的东西:

# yourapp/context_processors.py
# you can either use <from django.conf import settings> to make use of setting varibales

def static_vars(request):
    return {
        'var1': 'Hello',
        'var2': 'World',
    }

现在,在以 {{ var1 }} 访问模板中的变量之前,您必须将此函数传递给 TEMPLATES 设置,如下所示:

# settings.py

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        # dirs here
    ],
    'OPTIONS': {
        'context_processors': [
            # some other context processors here and ...
            'yourapp.context_processors.static_vars',
        ],
        'loaders': [
            # loaders here
        ],
    },
},

]

现在,您可以在每个模板中使用 static_vars 公开的变量。