1. =========
    
  2. Templates
    
  3. =========
    
  4. 
    
  5. .. module:: django.template
    
  6.     :synopsis: Django's template system
    
  7. 
    
  8. Being a web framework, Django needs a convenient way to generate HTML
    
  9. dynamically. The most common approach relies on templates. A template contains
    
  10. the static parts of the desired HTML output as well as some special syntax
    
  11. describing how dynamic content will be inserted. For a hands-on example of
    
  12. creating HTML pages with templates, see :doc:`Tutorial 3 </intro/tutorial03>`.
    
  13. 
    
  14. A Django project can be configured with one or several template engines (or
    
  15. even zero if you don't use templates). Django ships built-in backends for its
    
  16. own template system, creatively called the Django template language (DTL), and
    
  17. for the popular alternative Jinja2_. Backends for other template languages may
    
  18. be available from third-parties. You can also write your own custom backend,
    
  19. see :doc:`Custom template backend </howto/custom-template-backend>`
    
  20. 
    
  21. Django defines a standard API for loading and rendering templates regardless
    
  22. of the backend. Loading consists of finding the template for a given identifier
    
  23. and preprocessing it, usually compiling it to an in-memory representation.
    
  24. Rendering means interpolating the template with context data and returning the
    
  25. resulting string.
    
  26. 
    
  27. The :doc:`Django template language </ref/templates/language>` is Django's own
    
  28. template system. Until Django 1.8 it was the only built-in option available.
    
  29. It's a good template library even though it's fairly opinionated and sports a
    
  30. few idiosyncrasies. If you don't have a pressing reason to choose another
    
  31. backend, you should use the DTL, especially if you're writing a pluggable
    
  32. application and you intend to distribute templates. Django's contrib apps that
    
  33. include templates, like :doc:`django.contrib.admin </ref/contrib/admin/index>`,
    
  34. use the DTL.
    
  35. 
    
  36. For historical reasons, both the generic support for template engines and the
    
  37. implementation of the Django template language live in the ``django.template``
    
  38. namespace.
    
  39. 
    
  40. .. warning::
    
  41. 
    
  42.     The template system isn't safe against untrusted template authors. For
    
  43.     example, a site shouldn't allow its users to provide their own templates,
    
  44.     since template authors can do things like perform XSS attacks and access
    
  45.     properties of template variables that may contain sensitive information.
    
  46. 
    
  47. .. _template-language-intro:
    
  48. 
    
  49. The Django template language
    
  50. ============================
    
  51. 
    
  52. .. highlight:: html+django
    
  53. 
    
  54. Syntax
    
  55. ------
    
  56. 
    
  57. .. admonition:: About this section
    
  58. 
    
  59.     This is an overview of the Django template language's syntax. For details
    
  60.     see the :doc:`language syntax reference </ref/templates/language>`.
    
  61. 
    
  62. A Django template is a text document or a Python string marked-up using the
    
  63. Django template language. Some constructs are recognized and interpreted by the
    
  64. template engine. The main ones are variables and tags.
    
  65. 
    
  66. A template is rendered with a context. Rendering replaces variables with their
    
  67. values, which are looked up in the context, and executes tags. Everything else
    
  68. is output as is.
    
  69. 
    
  70. The syntax of the Django template language involves four constructs.
    
  71. 
    
  72. Variables
    
  73. ~~~~~~~~~
    
  74. 
    
  75. A variable outputs a value from the context, which is a dict-like object
    
  76. mapping keys to values.
    
  77. 
    
  78. Variables are surrounded by ``{{`` and ``}}`` like this::
    
  79. 
    
  80.     My first name is {{ first_name }}. My last name is {{ last_name }}.
    
  81. 
    
  82. With a context of ``{'first_name': 'John', 'last_name': 'Doe'}``, this template
    
  83. renders to::
    
  84. 
    
  85.     My first name is John. My last name is Doe.
    
  86. 
    
  87. Dictionary lookup, attribute lookup and list-index lookups are implemented with
    
  88. a dot notation::
    
  89. 
    
  90.     {{ my_dict.key }}
    
  91.     {{ my_object.attribute }}
    
  92.     {{ my_list.0 }}
    
  93. 
    
  94. If a variable resolves to a callable, the template system will call it with no
    
  95. arguments and use its result instead of the callable.
    
  96. 
    
  97. Tags
    
  98. ~~~~
    
  99. 
    
  100. Tags provide arbitrary logic in the rendering process.
    
  101. 
    
  102. This definition is deliberately vague. For example, a tag can output content,
    
  103. serve as a control structure e.g. an "if" statement or a "for" loop, grab
    
  104. content from a database, or even enable access to other template tags.
    
  105. 
    
  106. Tags are surrounded by ``{%`` and ``%}`` like this::
    
  107. 
    
  108.     {% csrf_token %}
    
  109. 
    
  110. Most tags accept arguments::
    
  111. 
    
  112.     {% cycle 'odd' 'even' %}
    
  113. 
    
  114. Some tags require beginning and ending tags::
    
  115. 
    
  116.     {% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %}
    
  117. 
    
  118. A :ref:`reference of built-in tags <ref-templates-builtins-tags>` is
    
  119. available as well as :ref:`instructions for writing custom tags
    
  120. <howto-writing-custom-template-tags>`.
    
  121. 
    
  122. Filters
    
  123. ~~~~~~~
    
  124. 
    
  125. Filters transform the values of variables and tag arguments.
    
  126. 
    
  127. They look like this::
    
  128. 
    
  129.      {{ django|title }}
    
  130. 
    
  131. With a context of ``{'django': 'the web framework for perfectionists with
    
  132. deadlines'}``, this template renders to::
    
  133. 
    
  134.     The Web Framework For Perfectionists With Deadlines
    
  135. 
    
  136. Some filters take an argument::
    
  137. 
    
  138.     {{ my_date|date:"Y-m-d" }}
    
  139. 
    
  140. A :ref:`reference of built-in filters <ref-templates-builtins-filters>` is
    
  141. available as well as :ref:`instructions for writing custom filters
    
  142. <howto-writing-custom-template-filters>`.
    
  143. 
    
  144. Comments
    
  145. ~~~~~~~~
    
  146. 
    
  147. Comments look like this::
    
  148. 
    
  149.     {# this won't be rendered #}
    
  150. 
    
  151. A :ttag:`{% comment %} <comment>` tag provides multi-line comments.
    
  152. 
    
  153. Components
    
  154. ----------
    
  155. 
    
  156. .. admonition:: About this section
    
  157. 
    
  158.     This is an overview of the Django template language's APIs. For details
    
  159.     see the :doc:`API reference </ref/templates/api>`.
    
  160. 
    
  161. Engine
    
  162. ~~~~~~
    
  163. 
    
  164. :class:`django.template.Engine` encapsulates an instance of the Django
    
  165. template system. The main reason for instantiating an
    
  166. :class:`~django.template.Engine` directly is to use the Django template
    
  167. language outside of a Django project.
    
  168. 
    
  169. :class:`django.template.backends.django.DjangoTemplates` is a thin wrapper
    
  170. adapting :class:`django.template.Engine` to Django's template backend API.
    
  171. 
    
  172. Template
    
  173. ~~~~~~~~
    
  174. 
    
  175. :class:`django.template.Template` represents a compiled template. Templates are
    
  176. obtained with :meth:`.Engine.get_template` or :meth:`.Engine.from_string`.
    
  177. 
    
  178. Likewise ``django.template.backends.django.Template`` is a thin wrapper
    
  179. adapting :class:`django.template.Template` to the common template API.
    
  180. 
    
  181. Context
    
  182. ~~~~~~~
    
  183. 
    
  184. :class:`django.template.Context` holds some metadata in addition to the context
    
  185. data. It is passed to :meth:`.Template.render` for rendering a template.
    
  186. 
    
  187. :class:`django.template.RequestContext` is a subclass of
    
  188. :class:`~django.template.Context` that stores the current
    
  189. :class:`~django.http.HttpRequest` and runs template context processors.
    
  190. 
    
  191. The common API doesn't have an equivalent concept. Context data is passed in a
    
  192. plain :class:`dict` and the current :class:`~django.http.HttpRequest` is passed
    
  193. separately if needed.
    
  194. 
    
  195. Loaders
    
  196. ~~~~~~~
    
  197. 
    
  198. Template loaders are responsible for locating templates, loading them, and
    
  199. returning :class:`~django.template.Template` objects.
    
  200. 
    
  201. Django provides several :ref:`built-in template loaders <template-loaders>`
    
  202. and supports :ref:`custom template loaders <custom-template-loaders>`.
    
  203. 
    
  204. Context processors
    
  205. ~~~~~~~~~~~~~~~~~~
    
  206. 
    
  207. Context processors are functions that receive the current
    
  208. :class:`~django.http.HttpRequest` as an argument and return a :class:`dict` of
    
  209. data to be added to the rendering context.
    
  210. 
    
  211. Their main use is to add common data shared by all templates to the context
    
  212. without repeating code in every view.
    
  213. 
    
  214. Django provides many :ref:`built-in context processors <context-processors>`,
    
  215. and you can implement your own additional context processors, too.
    
  216. 
    
  217. .. _template-engines:
    
  218. 
    
  219. Support for template engines
    
  220. ============================
    
  221. 
    
  222. .. highlight:: python
    
  223. 
    
  224. Configuration
    
  225. -------------
    
  226. 
    
  227. Templates engines are configured with the :setting:`TEMPLATES` setting. It's a
    
  228. list of configurations, one for each engine. The default value is empty. The
    
  229. ``settings.py`` generated by the :djadmin:`startproject` command defines a
    
  230. more useful value::
    
  231. 
    
  232.     TEMPLATES = [
    
  233.         {
    
  234.             'BACKEND': 'django.template.backends.django.DjangoTemplates',
    
  235.             'DIRS': [],
    
  236.             'APP_DIRS': True,
    
  237.             'OPTIONS': {
    
  238.                 # ... some options here ...
    
  239.             },
    
  240.         },
    
  241.     ]
    
  242. 
    
  243. :setting:`BACKEND <TEMPLATES-BACKEND>` is a dotted Python path to a template
    
  244. engine class implementing Django's template backend API. The built-in backends
    
  245. are :class:`django.template.backends.django.DjangoTemplates` and
    
  246. :class:`django.template.backends.jinja2.Jinja2`.
    
  247. 
    
  248. Since most engines load templates from files, the top-level configuration for
    
  249. each engine contains two common settings:
    
  250. 
    
  251. * :setting:`DIRS <TEMPLATES-DIRS>` defines a list of directories where the
    
  252.   engine should look for template source files, in search order.
    
  253. * :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` tells whether the engine should
    
  254.   look for templates inside installed applications. Each backend defines a
    
  255.   conventional name for the subdirectory inside applications where its
    
  256.   templates should be stored.
    
  257. 
    
  258. While uncommon, it's possible to configure several instances of the same
    
  259. backend with different options. In that case you should define a unique
    
  260. :setting:`NAME <TEMPLATES-NAME>` for each engine.
    
  261. 
    
  262. :setting:`OPTIONS <TEMPLATES-OPTIONS>` contains backend-specific settings.
    
  263. 
    
  264. .. _template-loading:
    
  265. 
    
  266. Usage
    
  267. -----
    
  268. 
    
  269. .. module:: django.template.loader
    
  270. 
    
  271. The ``django.template.loader`` module defines two functions to load templates.
    
  272. 
    
  273. .. function:: get_template(template_name, using=None)
    
  274. 
    
  275.     This function loads the template with the given name and returns a
    
  276.     ``Template`` object.
    
  277. 
    
  278.     The exact type of the return value depends on the backend that loaded the
    
  279.     template. Each backend has its own ``Template`` class.
    
  280. 
    
  281.     ``get_template()`` tries each template engine in order until one succeeds.
    
  282.     If the template cannot be found, it raises
    
  283.     :exc:`~django.template.TemplateDoesNotExist`. If the template is found but
    
  284.     contains invalid syntax, it raises
    
  285.     :exc:`~django.template.TemplateSyntaxError`.
    
  286. 
    
  287.     How templates are searched and loaded depends on each engine's backend and
    
  288.     configuration.
    
  289. 
    
  290.     If you want to restrict the search to a particular template engine, pass
    
  291.     the engine's :setting:`NAME <TEMPLATES-NAME>` in the ``using`` argument.
    
  292. 
    
  293. .. function:: select_template(template_name_list, using=None)
    
  294. 
    
  295.     ``select_template()`` is just like ``get_template()``, except it takes a
    
  296.     list of template names. It tries each name in order and returns the first
    
  297.     template that exists.
    
  298. 
    
  299. .. currentmodule:: django.template
    
  300. 
    
  301. If loading a template fails, the following two exceptions, defined in
    
  302. ``django.template``, may be raised:
    
  303. 
    
  304. .. exception:: TemplateDoesNotExist(msg, tried=None, backend=None, chain=None)
    
  305. 
    
  306.     This exception is raised when a template cannot be found. It accepts the
    
  307.     following optional arguments for populating the :ref:`template postmortem
    
  308.     <template-postmortem>` on the debug page:
    
  309. 
    
  310.     ``backend``
    
  311.         The template backend instance from which the exception originated.
    
  312. 
    
  313.     ``tried``
    
  314.         A list of sources that were tried when finding the template. This is
    
  315.         formatted as a list of tuples containing ``(origin, status)``, where
    
  316.         ``origin`` is an :ref:`origin-like <template-origin-api>` object and
    
  317.         ``status`` is a string with the reason the template wasn't found.
    
  318. 
    
  319.     ``chain``
    
  320.         A list of intermediate :exc:`~django.template.TemplateDoesNotExist`
    
  321.         exceptions raised when trying to load a template. This is used by
    
  322.         functions, such as :func:`~django.template.loader.get_template`, that
    
  323.         try to load a given template from multiple engines.
    
  324. 
    
  325. .. exception:: TemplateSyntaxError(msg)
    
  326. 
    
  327.     This exception is raised when a template was found but contains errors.
    
  328. 
    
  329. ``Template`` objects returned by ``get_template()`` and ``select_template()``
    
  330. must provide a ``render()`` method with the following signature:
    
  331. 
    
  332. .. currentmodule:: django.template.backends.base
    
  333. 
    
  334. .. method:: Template.render(context=None, request=None)
    
  335. 
    
  336.     Renders this template with a given context.
    
  337. 
    
  338.     If ``context`` is provided, it must be a :class:`dict`. If it isn't
    
  339.     provided, the engine will render the template with an empty context.
    
  340. 
    
  341.     If ``request`` is provided, it must be an :class:`~django.http.HttpRequest`.
    
  342.     Then the engine must make it, as well as the CSRF token, available in the
    
  343.     template. How this is achieved is up to each backend.
    
  344. 
    
  345. Here's an example of the search algorithm. For this example the
    
  346. :setting:`TEMPLATES` setting is::
    
  347. 
    
  348.     TEMPLATES = [
    
  349.         {
    
  350.             'BACKEND': 'django.template.backends.django.DjangoTemplates',
    
  351.             'DIRS': [
    
  352.                 '/home/html/example.com',
    
  353.                 '/home/html/default',
    
  354.             ],
    
  355.         },
    
  356.         {
    
  357.             'BACKEND': 'django.template.backends.jinja2.Jinja2',
    
  358.             'DIRS': [
    
  359.                 '/home/html/jinja2',
    
  360.             ],
    
  361.         },
    
  362.     ]
    
  363. 
    
  364. If you call ``get_template('story_detail.html')``, here are the files Django
    
  365. will look for, in order:
    
  366. 
    
  367. * ``/home/html/example.com/story_detail.html`` (``'django'`` engine)
    
  368. * ``/home/html/default/story_detail.html`` (``'django'`` engine)
    
  369. * ``/home/html/jinja2/story_detail.html`` (``'jinja2'`` engine)
    
  370. 
    
  371. If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
    
  372. here's what Django will look for:
    
  373. 
    
  374. * ``/home/html/example.com/story_253_detail.html`` (``'django'`` engine)
    
  375. * ``/home/html/default/story_253_detail.html`` (``'django'`` engine)
    
  376. * ``/home/html/jinja2/story_253_detail.html`` (``'jinja2'`` engine)
    
  377. * ``/home/html/example.com/story_detail.html`` (``'django'`` engine)
    
  378. * ``/home/html/default/story_detail.html`` (``'django'`` engine)
    
  379. * ``/home/html/jinja2/story_detail.html`` (``'jinja2'`` engine)
    
  380. 
    
  381. When Django finds a template that exists, it stops looking.
    
  382. 
    
  383. .. admonition:: Tip
    
  384. 
    
  385.     You can use :func:`~django.template.loader.select_template()` for flexible
    
  386.     template loading. For example, if you've written a news story and want
    
  387.     some stories to have custom templates, use something like
    
  388.     ``select_template(['story_%s_detail.html' % story.id,
    
  389.     'story_detail.html'])``. That'll allow you to use a custom template for an
    
  390.     individual story, with a fallback template for stories that don't have
    
  391.     custom templates.
    
  392. 
    
  393. It's possible -- and preferable -- to organize templates in subdirectories
    
  394. inside each directory containing templates. The convention is to make a
    
  395. subdirectory for each Django app, with subdirectories within those
    
  396. subdirectories as needed.
    
  397. 
    
  398. Do this for your own sanity. Storing all templates in the root level of a
    
  399. single directory gets messy.
    
  400. 
    
  401. To load a template that's within a subdirectory, use a slash, like so::
    
  402. 
    
  403.     get_template('news/story_detail.html')
    
  404. 
    
  405. Using the same :setting:`TEMPLATES` option as above, this will attempt to load
    
  406. the following templates:
    
  407. 
    
  408. * ``/home/html/example.com/news/story_detail.html`` (``'django'`` engine)
    
  409. * ``/home/html/default/news/story_detail.html`` (``'django'`` engine)
    
  410. * ``/home/html/jinja2/news/story_detail.html`` (``'jinja2'`` engine)
    
  411. 
    
  412. .. currentmodule:: django.template.loader
    
  413. 
    
  414. In addition, to cut down on the repetitive nature of loading and rendering
    
  415. templates, Django provides a shortcut function which automates the process.
    
  416. 
    
  417. .. function:: render_to_string(template_name, context=None, request=None, using=None)
    
  418. 
    
  419.     ``render_to_string()`` loads a template like :func:`get_template` and
    
  420.     calls its ``render()`` method immediately. It takes the following
    
  421.     arguments.
    
  422. 
    
  423.     ``template_name``
    
  424.         The name of the template to load and render. If it's a list of template
    
  425.         names, Django uses :func:`select_template` instead of
    
  426.         :func:`get_template` to find the template.
    
  427. 
    
  428.     ``context``
    
  429.         A :class:`dict` to be used as the template's context for rendering.
    
  430. 
    
  431.     ``request``
    
  432.         An optional :class:`~django.http.HttpRequest` that will be available
    
  433.         during the template's rendering process.
    
  434. 
    
  435.     ``using``
    
  436.         An optional template engine :setting:`NAME <TEMPLATES-NAME>`. The
    
  437.         search for the template will be restricted to that engine.
    
  438. 
    
  439.     Usage example::
    
  440. 
    
  441.         from django.template.loader import render_to_string
    
  442.         rendered = render_to_string('my_template.html', {'foo': 'bar'})
    
  443. 
    
  444. See also the :func:`~django.shortcuts.render()` shortcut which calls
    
  445. :func:`render_to_string()` and feeds the result into an
    
  446. :class:`~django.http.HttpResponse` suitable for returning from a view.
    
  447. 
    
  448. Finally, you can use configured engines directly:
    
  449. 
    
  450. .. data:: engines
    
  451. 
    
  452.     Template engines are available in ``django.template.engines``::
    
  453. 
    
  454.         from django.template import engines
    
  455. 
    
  456.         django_engine = engines['django']
    
  457.         template = django_engine.from_string("Hello {{ name }}!")
    
  458. 
    
  459.     The lookup key — ``'django'`` in this example — is the engine's
    
  460.     :setting:`NAME <TEMPLATES-NAME>`.
    
  461. 
    
  462. .. module:: django.template.backends
    
  463. 
    
  464. Built-in backends
    
  465. -----------------
    
  466. 
    
  467. .. module:: django.template.backends.django
    
  468. 
    
  469. .. class:: DjangoTemplates
    
  470. 
    
  471. Set :setting:`BACKEND <TEMPLATES-BACKEND>` to
    
  472. ``'django.template.backends.django.DjangoTemplates'`` to configure a Django
    
  473. template engine.
    
  474. 
    
  475. When :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is ``True``, ``DjangoTemplates``
    
  476. engines look for templates in the ``templates`` subdirectory of installed
    
  477. applications. This generic name was kept for backwards-compatibility.
    
  478. 
    
  479. ``DjangoTemplates`` engines accept the following :setting:`OPTIONS
    
  480. <TEMPLATES-OPTIONS>`:
    
  481. 
    
  482. * ``'autoescape'``: a boolean that controls whether HTML autoescaping is
    
  483.   enabled.
    
  484. 
    
  485.   It defaults to ``True``.
    
  486. 
    
  487.   .. warning::
    
  488. 
    
  489.       Only set it to ``False`` if you're rendering non-HTML templates!
    
  490. 
    
  491. * ``'context_processors'``: a list of dotted Python paths to callables that
    
  492.   are used to populate the context when a template is rendered with a request.
    
  493.   These callables take a request object as their argument and return a
    
  494.   :class:`dict` of items to be merged into the context.
    
  495. 
    
  496.   It defaults to an empty list.
    
  497. 
    
  498.   See :class:`~django.template.RequestContext` for more information.
    
  499. 
    
  500. * ``'debug'``: a boolean that turns on/off template debug mode. If it is
    
  501.   ``True``, the fancy error page will display a detailed report for any
    
  502.   exception raised during template rendering. This report contains the
    
  503.   relevant snippet of the template with the appropriate line highlighted.
    
  504. 
    
  505.   It defaults to the value of the :setting:`DEBUG` setting.
    
  506. 
    
  507. * ``'loaders'``: a list of dotted Python paths to template loader classes.
    
  508.   Each ``Loader`` class knows how to import templates from a particular
    
  509.   source. Optionally, a tuple can be used instead of a string. The first item
    
  510.   in the tuple should be the ``Loader`` class name, and subsequent items are
    
  511.   passed to the ``Loader`` during initialization.
    
  512. 
    
  513.   The default depends on the values of :setting:`DIRS <TEMPLATES-DIRS>` and
    
  514.   :setting:`APP_DIRS <TEMPLATES-APP_DIRS>`.
    
  515. 
    
  516.   See :ref:`template-loaders` for details.
    
  517. 
    
  518. * ``'string_if_invalid'``: the output, as a string, that the template system
    
  519.   should use for invalid (e.g. misspelled) variables.
    
  520. 
    
  521.   It defaults to an empty string.
    
  522. 
    
  523.   See :ref:`invalid-template-variables` for details.
    
  524. 
    
  525. * ``'file_charset'``: the charset used to read template files on disk.
    
  526. 
    
  527.   It defaults to ``'utf-8'``.
    
  528. 
    
  529. * ``'libraries'``: A dictionary of labels and dotted Python paths of template
    
  530.   tag modules to register with the template engine. This can be used to add
    
  531.   new libraries or provide alternate labels for existing ones. For example::
    
  532. 
    
  533.       OPTIONS={
    
  534.           'libraries': {
    
  535.               'myapp_tags': 'path.to.myapp.tags',
    
  536.               'admin.urls': 'django.contrib.admin.templatetags.admin_urls',
    
  537.           },
    
  538.       }
    
  539. 
    
  540.   Libraries can be loaded by passing the corresponding dictionary key to
    
  541.   the :ttag:`{% load %}<load>` tag.
    
  542. 
    
  543. * ``'builtins'``: A list of dotted Python paths of template tag modules to
    
  544.   add to :doc:`built-ins </ref/templates/builtins>`. For example::
    
  545. 
    
  546.       OPTIONS={
    
  547.           'builtins': ['myapp.builtins'],
    
  548.       }
    
  549. 
    
  550.   Tags and filters from built-in libraries can be used without first calling
    
  551.   the :ttag:`{% load %} <load>` tag.
    
  552. 
    
  553. .. module:: django.template.backends.jinja2
    
  554. 
    
  555. .. class:: Jinja2
    
  556. 
    
  557. Requires Jinja2_ to be installed:
    
  558. 
    
  559. .. console::
    
  560. 
    
  561.     $ python -m pip install Jinja2
    
  562. 
    
  563. Set :setting:`BACKEND <TEMPLATES-BACKEND>` to
    
  564. ``'django.template.backends.jinja2.Jinja2'`` to configure a Jinja2_ engine.
    
  565. 
    
  566. When :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is ``True``, ``Jinja2`` engines
    
  567. look for templates in the ``jinja2`` subdirectory of installed applications.
    
  568. 
    
  569. The most important entry in :setting:`OPTIONS <TEMPLATES-OPTIONS>` is
    
  570. ``'environment'``. It's a dotted Python path to a callable returning a Jinja2
    
  571. environment. It defaults to ``'jinja2.Environment'``. Django invokes that
    
  572. callable and passes other options as keyword arguments. Furthermore, Django
    
  573. adds defaults that differ from Jinja2's for a few options:
    
  574. 
    
  575. * ``'autoescape'``: ``True``
    
  576. * ``'loader'``: a loader configured for :setting:`DIRS <TEMPLATES-DIRS>` and
    
  577.   :setting:`APP_DIRS <TEMPLATES-APP_DIRS>`
    
  578. * ``'auto_reload'``: ``settings.DEBUG``
    
  579. * ``'undefined'``: ``DebugUndefined if settings.DEBUG else Undefined``
    
  580. 
    
  581. ``Jinja2`` engines also accept the following :setting:`OPTIONS
    
  582. <TEMPLATES-OPTIONS>`:
    
  583. 
    
  584. * ``'context_processors'``: a list of dotted Python paths to callables that
    
  585.   are used to populate the context when a template is rendered with a request.
    
  586.   These callables take a request object as their argument and return a
    
  587.   :class:`dict` of items to be merged into the context.
    
  588. 
    
  589.   It defaults to an empty list.
    
  590. 
    
  591.   .. admonition:: Using context processors with Jinja2 templates is discouraged.
    
  592. 
    
  593.     Context processors are useful with Django templates because Django templates
    
  594.     don't support calling functions with arguments. Since Jinja2 doesn't have
    
  595.     that limitation, it's recommended to put the function that you would use as a
    
  596.     context processor in the global variables available to the template using
    
  597.     ``jinja2.Environment`` as described below. You can then call that function in
    
  598.     the template:
    
  599. 
    
  600.     .. code-block:: jinja
    
  601. 
    
  602.       {{ function(request) }}
    
  603. 
    
  604.     Some Django templates context processors return a fixed value. For Jinja2
    
  605.     templates, this layer of indirection isn't necessary since you can add
    
  606.     constants directly in ``jinja2.Environment``.
    
  607. 
    
  608.     The original use case for adding context processors for Jinja2 involved:
    
  609. 
    
  610.     * Making an expensive computation that depends on the request.
    
  611.     * Needing the result in every template.
    
  612.     * Using the result multiple times in each template.
    
  613. 
    
  614.     Unless all of these conditions are met, passing a function to the template is
    
  615.     more in line with the design of Jinja2.
    
  616. 
    
  617. The default configuration is purposefully kept to a minimum. If a template is
    
  618. rendered with a request (e.g. when using :py:func:`~django.shortcuts.render`),
    
  619. the ``Jinja2`` backend adds the globals ``request``, ``csrf_input``, and
    
  620. ``csrf_token`` to the context. Apart from that, this backend doesn't create a
    
  621. Django-flavored environment. It doesn't know about Django filters and tags.
    
  622. In order to use Django-specific APIs, you must configure them into the
    
  623. environment.
    
  624. 
    
  625. For example, you can create ``myproject/jinja2.py`` with this content::
    
  626. 
    
  627.     from django.templatetags.static import static
    
  628.     from django.urls import reverse
    
  629. 
    
  630.     from jinja2 import Environment
    
  631. 
    
  632. 
    
  633.     def environment(**options):
    
  634.         env = Environment(**options)
    
  635.         env.globals.update({
    
  636.             'static': static,
    
  637.             'url': reverse,
    
  638.         })
    
  639.         return env
    
  640. 
    
  641. and set the ``'environment'`` option to ``'myproject.jinja2.environment'``.
    
  642. 
    
  643. Then you could use the following constructs in Jinja2 templates:
    
  644. 
    
  645. .. code-block:: html+jinja
    
  646. 
    
  647.     <img src="{{ static('path/to/company-logo.png') }}" alt="Company Logo">
    
  648. 
    
  649.     <a href="{{ url('admin:index') }}">Administration</a>
    
  650. 
    
  651. The concepts of tags and filters exist both in the Django template language
    
  652. and in Jinja2 but they're used differently. Since Jinja2 supports passing
    
  653. arguments to callables in templates, many features that require a template tag
    
  654. or filter in Django templates can be achieved by calling a function in Jinja2
    
  655. templates, as shown in the example above. Jinja2's global namespace removes the
    
  656. need for template context processors. The Django template language doesn't have
    
  657. an equivalent of Jinja2 tests.
    
  658. 
    
  659. .. _Jinja2: https://jinja.palletsprojects.com/