How can i pass data to django layouts (like 'base.html') without having to provide it through every view?

核能气质少年 提交于 2019-11-30 03:42:01

Use a context processor, which is made exactly for that purpose. Create a file context_processors.py in one of your app directories, then in the file define a function that return a dictionary of variables to insert in every template context, something like this:

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

Enable your context processor in the settings (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',
            ],
        },
    },
]

Then in every template you can write

{{ testme }}

And it will render as

Hello world!

More info in the Django documentation

If you need this data in (almost) every template, then it makes sense to use a context processor. From the django docs:

The context_processors option is a list of callables – called context processors – that take a request object as their argument and return a dictionary of items to be merged into the context.

Django docs on Writing your own context processors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!