Sachin K Sachin K -4 years ago 76
HTML Question

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

I am trying to pass the data to layout 'base.html'. I am currently doing it by storing the data in request.session and accessing it in 'base.html' through request object. Is there any way to pass the data to 'base.html' without having to pass the data from every views.

Answer Source

Use a context processor, which is made exactly for that purpose. Create a file 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):

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [root('templates'),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

Then in every template you can write

{{ testme }}

And it will render as

Hello world!

More info in the Django documentation

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download