class Jinja2
[source]
Requires Jinja2 to be installed:
$ pip install Jinja2
Set BACKEND
to 'django.template.backends.jinja2.Jinja2'
to configure a Jinja2 engine.
When APP_DIRS
is True
, Jinja2
engines look for templates in the jinja2
subdirectory of installed applications.
The most important entry in OPTIONS
is 'environment'
. It’s a dotted Python path to a callable returning a Jinja2 environment. It defaults to 'jinja2.Environment'
. Django invokes that callable and passes other options as keyword arguments. Furthermore, Django adds defaults that differ from Jinja2’s for a few options:
-
'autoescape'
:True
-
'loader'
: a loader configured forDIRS
andAPP_DIRS
-
'auto_reload'
:settings.DEBUG
-
'undefined'
:DebugUndefined if settings.DEBUG else Undefined
The default configuration is purposefully kept to a minimum. If a template is rendered with a request (e.g. when using render()
), the Jinja2
backend adds the globals request
, csrf_input
, and csrf_token
to the context. Apart from that, this backend doesn’t create a Django-flavored environment. It doesn’t know about Django context processors, filters, and tags. In order to use Django-specific APIs, you must configure them into the environment.
For example, you can create myproject/jinja2.py
with this content:
from __future__ import absolute_import # Python 2 only from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from jinja2 import Environment def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) return env
and set the 'environment'
option to 'myproject.jinja2.environment'
.
Then you could use the following constructs in Jinja2 templates:
<img src="{{ static('path/to/company-logo.png') }}" alt="Company Logo"> <a href="{{ url('admin:index') }}">Administration</a>
The concepts of tags and filters exist both in the Django template language and in Jinja2 but they’re used differently. Since Jinja2 supports passing arguments to callables in templates, many features that require a template tag or filter in Django templates can be achieved simply by calling a function in Jinja2 templates, as shown in the example above. Jinja2’s global namespace removes the need for template context processors. The Django template language doesn’t have an equivalent of Jinja2 tests.
Please login to continue.