From 9fbd302f91162434f375b67a533d4a955a439484 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Sun, 15 Feb 2015 17:31:06 +0100 Subject: [PATCH] Documented how to set up the Jinja2 environment. This may also help with "Why do context processors not work in Jinja2 templates?" etc. --- docs/topics/templates.txt | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/docs/topics/templates.txt b/docs/topics/templates.txt index 6be5d6165d..0b01ea53c2 100644 --- a/docs/topics/templates.txt +++ b/docs/topics/templates.txt @@ -404,6 +404,45 @@ adds defaults that differ from Jinja2's for a few options: * ``'auto_reload'``: ``settings.DEBUG`` * ``'undefined'``: ``DebugUndefined if settings.DEBUG else Undefined`` +The default configuration is purposefully kept to a minimum. The ``Jinja2`` +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 django.contrib.staticfiles.storage import staticfiles_storage + from django.core.urlresolvers 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: + +.. code-block:: html+jinja + + Company Logo + + Administration + +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. + Custom backends ---------------