Search code examples
djangodjango-templatesdjango-apps

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


I'm looking for a way to set a number of site-wide (or app-wide) variables, such as website (or app) title for instance, that I would use in my templates (in my header for instance). I have something like WordPress' bloginfo() in mind.

Ideally I'd like to be able to define any type of attribute at the level of a site or an app. For a given app, for instance, I'd have :

app

--attribute1 (e.g. title)

--attribute2 (e.g. contact email)

--Model1

----AttributeX

----AttributeY

----...

Meaning that "attribute1" would be unique to my app. I would then need a way to use the value of attribute1 in my templates. I hope my question is clear.


Solution

  • I use site-wide (or app-wide) variables all the time using context processors.

    Inside your app create a separate file called context_processors.py (needless to say that isn't mandatory to name it like that, it is just for convention) and this file must define at least one function which accepts a request parameter and returns a dictionary.

    Something like that:

    # 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',
        }
    

    Now before you access the variables in your templates as {{ var1 }}, you must pass this function to the TEMPLATES settings like this:

    # 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
            ],
        },
    },
    

    ]

    Now, you can use the variables static_vars expose in every template.