如何将数据传递到django布局(如'base.html')而不必通过每个视图提供它?

Sac*_*n K 13 html django django-templates django-views

我试图将数据传递给布局'base.html'.我目前正在通过将数据存储request.session'base.html'请求对象中并通过请求对象访问它来实现.

有没有办法传递数据'base.html'而不必从每个视图传递数据?

bax*_*ico 22

使用完全为此目的而制作的上下文处理器.context_processors.py在您的某个app目录中创建一个文件,然后在该文件中定义一个函数,该函数返回要在每个模板上下文中插入的变量字典,如下所示:

def add_variable_to_context(request):
    return {
        'testme': 'Hello world!'
    }
Run Code Online (Sandbox Code Playgroud)

在设置中启用上下文处理器(django> = 1.8):

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [root('templates'),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'yourapp.context_processors.add_variable_to_context',
            ],
        },
    },
]
Run Code Online (Sandbox Code Playgroud)

然后在每个模板中你都可以写

{{ testme }}

它将呈现为

Hello world!

Django文档中的更多信息

  • @HassanBaig,您可以根据需要自定义“add_variable_to_context”函数。例如,您可以导入 Django 模型、执行一些查询并在每个模板中注入一些动态内容。在示例中,我使用字符串文字只是为了使代码易于理解。 (2认同)