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

时间:2016-01-20 14:27:05

标签: html django django-templates django-views

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

有没有办法将数据传递给'base.html'而无需从每个视图传递数据?

3 个答案:

答案 0 :(得分:17)

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

def add_variable_to_context(request):
    return {
        'testme': 'Hello world!'
    }

在设置中启用上下文处理器(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',
            ],
        },
    },
]

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

{{ testme }}

它将呈现为

Hello world!

Django documentation

中的更多信息

答案 1 :(得分:1)

如果您(几乎)每个模板都需要这些数据,那么使用上下文处理器是有意义的。来自django docs:

  

context_processors选项是一个可调用的列表 - 称为上下文处理器 - 它将请求对象作为其参数,并返回要合并到上下文中的项的字典。

Django docs on Writing your own context processors

答案 2 :(得分:-1)

from django.shortcuts import render_to_response

env = {'name': 'Your Name'}

return render_to_response('base.html', env)

这只会将名称发送到页面base.html