Jinja globals: Access data on all Jinja templates, like Django context processors

Just like Django templates offer context processors to facilitate the access of data on all Django templates, Jinja also offers its own version of the same feature which is called globals. Jinja in its out-of-the-box state has no globals, but in its Django integrated mode includes three globals to mimic Django's most common context processors, these globals are: request, csrf_input and csrf_token.

This means you get access to three Django context processor 'like variables in all Jinja templates used in Django projects. However, to set up additional global variables you need to work with Jinja's environment.

To set up Jinja globals you need to access Jinja's environment which is where globals are stored, in a variable properly called globals. By default, the Django-Jinja configuration uses Jinja's built-in jinja2.Environment environment. In order to access Jinja's environment in Django and set globals, the easiest path is to create your own Jinja environment and use it to initialize the Django-Jinja configuration. Listing 4-11 illustrate a custom Jinja environment class which sets the global variables named static and url.

Listing 4-11 Custom Jinja environment with global variable

from jinja2.environment import Environment
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse

class JinjaEnvironment(Environment):
    def __init__(self,**kwargs):
        super(JinjaEnvironment, self).__init__(**kwargs)
        self.globals['static'] = staticfiles_storage.url
        self.globals['url'] = reverse

As you can see in listing 4-11, the custom JinjaEnvironment class is a sub-class of the jinja2.Environment class, this is so the custom class inherits the bulk of its features from this base class provided by Jinja. Next, you can see we use the __init__ method to initialize the base class.