templates.txt 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. =========
  2. Templates
  3. =========
  4. .. module:: django.template
  5. :synopsis: Django's template system
  6. Being a web framework, Django needs a convenient way to generate HTML
  7. dynamically. The most common approach relies on templates. A template contains
  8. the static parts of the desired HTML output as well as some special syntax
  9. describing how dynamic content will be inserted. For a hands-on example of
  10. creating HTML pages with templates, see :doc:`Tutorial 3 </intro/tutorial03>`.
  11. A Django project can be configured with one or several template engines (or
  12. even zero if you don't use templates). Django ships built-in backends for its
  13. own template system, creatively called the Django template language (DTL), and
  14. for the popular alternative Jinja2_. Backends for other template languages may
  15. be available from third-parties.
  16. Django defines a standard API for loading and rendering templates regardless
  17. of the backend. Loading consists of finding the template for a given identifier
  18. and preprocessing it, usually compiling it to an in-memory representation.
  19. Rendering means interpolating the template with context data and returning the
  20. resulting string.
  21. The :doc:`Django template language </ref/templates/language>` is Django's own
  22. template system. Until Django 1.8 it was the only built-in option available.
  23. It's a good template library even though it's fairly opinionated and sports a
  24. few idiosyncrasies. If you don't have a pressing reason to choose another
  25. backend, you should use the DTL, especially if you're writing a pluggable
  26. application and you intend to distribute templates. Django's contrib apps that
  27. include templates, like :doc:`django.contrib.admin </ref/contrib/admin/index>`,
  28. use the DTL.
  29. For historical reasons, both the generic support for template engines and the
  30. implementation of the Django template language live in the ``django.template``
  31. namespace.
  32. .. _template-engines:
  33. Support for template engines
  34. ============================
  35. .. versionadded:: 1.8
  36. Support for multiple template engines and the :setting:`TEMPLATES` setting
  37. were added in Django 1.8.
  38. Configuration
  39. -------------
  40. Templates engines are configured with the :setting:`TEMPLATES` setting. It's a
  41. list of configurations, one for each engine. The default value is empty. The
  42. ``settings.py`` generated by the :djadmin:`startproject` command defines a
  43. more useful value::
  44. TEMPLATES = [
  45. {
  46. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  47. 'DIRS': [],
  48. 'APP_DIRS': True,
  49. 'OPTIONS': {
  50. # ... some options here ...
  51. },
  52. },
  53. ]
  54. :setting:`BACKEND <TEMPLATES-BACKEND>` is a dotted Python path to a template
  55. engine class implementing Django's template backend API. The built-in backends
  56. are :class:`django.template.backends.django.DjangoTemplates` and
  57. :class:`django.template.backends.jinja2.Jinja2`.
  58. Since most engines load templates from files, the top-level configuration for
  59. each engine contains two common settings:
  60. * :setting:`DIRS <TEMPLATES-DIRS>` defines a list of directories where the
  61. engine should look for template source files, in search order.
  62. * :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` tells whether the engine should
  63. look for templates inside installed applications. Each backend defines a
  64. conventional name for the subdirectory inside applications where its
  65. templates should be stored.
  66. While uncommon, it's possible to configure several instances of the same
  67. backend with different options. In that case you should define a unique
  68. :setting:`NAME <TEMPLATES-NAME>` for each engine.
  69. :setting:`OPTIONS <TEMPLATES-OPTIONS>` contains backend-specific settings.
  70. Usage
  71. -----
  72. .. _template-loading:
  73. .. module:: django.template.loader
  74. The ``django.template.loader`` module defines two functions to load templates.
  75. .. function:: get_template(template_name[, dirs][, using])
  76. This function loads the template with the given name and returns a
  77. ``Template`` object.
  78. The exact type of the return value depends on the backend that loaded the
  79. template. Each backend has its own ``Template`` class.
  80. ``get_template()`` tries each template engine in order until one succeeds.
  81. If the template cannot be found, it raises
  82. :exc:`~django.template.TemplateDoesNotExist`. If the template is found but
  83. contains invalid syntax, it raises
  84. :exc:`~django.template.TemplateSyntaxError`.
  85. How templates are searched and loaded depends on each engine's backend and
  86. configuration.
  87. If you want to restrict the search to a particular template engine, pass
  88. the engine's :setting:`NAME <TEMPLATES-NAME>` in the ``using`` argument.
  89. .. deprecated:: 1.8
  90. The ``dirs`` parameter was deprecated.
  91. .. versionchanged:: 1.8
  92. The ``using`` parameter was added.
  93. .. versionchanged:: 1.8
  94. ``get_template()`` returns a backend-dependent ``Template`` instead
  95. of a :class:`django.template.Template`.
  96. .. function:: select_template(template_name_list[, dirs][, using])
  97. ``select_template()`` is just like ``get_template()``, except it takes a
  98. list of template names. It tries each name in order and returns the first
  99. template that exists.
  100. .. deprecated:: 1.8
  101. The ``dirs`` parameter was deprecated.
  102. .. versionchanged:: 1.8
  103. The ``using`` parameter was added.
  104. .. versionchanged:: 1.8
  105. ``select_template()`` returns a backend-dependent ``Template`` instead
  106. of a :class:`django.template.Template`.
  107. .. currentmodule:: django.template
  108. If loading a template fails, the following two exceptions, defined in
  109. ``django.template``, may be raised:
  110. .. exception:: TemplateDoesNotExist
  111. This exception is raised when a template cannot be found.
  112. .. exception:: TemplateSyntaxError
  113. This exception is raised when a template was found but contains errors.
  114. ``Template`` objects returned by ``get_template()`` and ``select_template()``
  115. must provide a ``render()`` method with the following signature:
  116. .. currentmodule:: django.template.backends.base
  117. .. method:: Template.render(context=None, request=None)
  118. Renders this template with a given context.
  119. If ``context`` is provided, it must be a :class:`dict`. If it isn't
  120. provided, the engine will render the template with an empty context.
  121. If ``request`` is provided, it must be an :class:`~django.http.HttpRequest`.
  122. Then the engine must make it, as well as the CSRF token, available in the
  123. template. How this is achieved is up to each backend.
  124. Here's an example of the search algorithm. For this example the
  125. :setting:`TEMPLATES` setting is::
  126. TEMPLATES = [
  127. {
  128. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  129. 'DIRS': [
  130. '/home/html/example.com',
  131. '/home/html/default',
  132. ],
  133. },
  134. {
  135. 'BACKEND': 'django.template.backends.jinja2.Jinja2',
  136. 'DIRS': [
  137. '/home/html/jinja2',
  138. ],
  139. },
  140. ]
  141. If you call ``get_template('story_detail.html')``, here are the files Django
  142. will look for, in order:
  143. * ``/home/html/example.com/story_detail.html`` (``'django'`` engine)
  144. * ``/home/html/default/story_detail.html`` (``'django'`` engine)
  145. * ``/home/html/jinja2/story_detail.html`` (``'jinja2'`` engine)
  146. If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
  147. here's what Django will look for:
  148. * ``/home/html/example.com/story_253_detail.html`` (``'django'`` engine)
  149. * ``/home/html/default/story_253_detail.html`` (``'django'`` engine)
  150. * ``/home/html/jinja2/story_253_detail.html`` (``'jinja2'`` engine)
  151. * ``/home/html/example.com/story_detail.html`` (``'django'`` engine)
  152. * ``/home/html/default/story_detail.html`` (``'django'`` engine)
  153. * ``/home/html/jinja2/story_detail.html`` (``'jinja2'`` engine)
  154. When Django finds a template that exists, it stops looking.
  155. .. admonition:: Tip
  156. You can use :func:`~django.template.loader.select_template()` for flexible
  157. template loading. For example, if you've written a news story and want
  158. some stories to have custom templates, use something like
  159. ``select_template(['story_%s_detail.html' % story.id,
  160. 'story_detail.html'])``. That'll allow you to use a custom template for an
  161. individual story, with a fallback template for stories that don't have
  162. custom templates.
  163. It's possible -- and preferable -- to organize templates in subdirectories
  164. inside each directory containing templates. The convention is to make a
  165. subdirectory for each Django app, with subdirectories within those
  166. subdirectories as needed.
  167. Do this for your own sanity. Storing all templates in the root level of a
  168. single directory gets messy.
  169. To load a template that's within a subdirectory, just use a slash, like so::
  170. get_template('news/story_detail.html')
  171. Using the same :setting:`TEMPLATES` option as above, this will attempt to load
  172. the following templates:
  173. * ``/home/html/example.com/news/story_detail.html`` (``'django'`` engine)
  174. * ``/home/html/default/news/story_detail.html`` (``'django'`` engine)
  175. * ``/home/html/jinja2/news/story_detail.html`` (``'jinja2'`` engine)
  176. .. currentmodule:: django.template.loader
  177. In addition, to cut down on the repetitive nature of loading and rendering
  178. templates, Django provides a shortcut function which automates the process.
  179. .. function:: render_to_string(template_name[, context][, context_instance][, request][, using])
  180. ``render_to_string()`` loads a template like :func:`get_template` and
  181. calls its ``render()`` method immediately. It takes the following
  182. arguments.
  183. ``template_name``
  184. The name of the template to load and render. If it's a list of template
  185. names, Django uses :func:`select_template` instead of
  186. :func:`get_template` to find the template.
  187. ``context``
  188. A :class:`dict` to be used as the template's context for rendering.
  189. .. versionchanged:: 1.8
  190. The ``context`` argument used to be called ``dictionary``. That name
  191. is deprecated in Django 1.8 and will be removed in Django 2.0.
  192. ``context`` is now optional. An empty context will be used if it
  193. isn't provided.
  194. ``context_instance``
  195. An instance of :class:`~django.template.Context` or a subclass (e.g., an
  196. instance of :class:`~django.template.RequestContext`) to use as the
  197. template's context.
  198. .. deprecated:: 1.8
  199. The ``context_instance`` argument is deprecated. Use ``context`` and
  200. if needed ``request``.
  201. ``request``
  202. An optional :class:`~django.http.HttpRequest` that will be available
  203. during the template's rendering process.
  204. .. versionadded:: 1.8
  205. The ``request`` argument was added.
  206. See also the :func:`~django.shortcuts.render()` and
  207. :func:`~django.shortcuts.render_to_response()` shortcuts, which call
  208. :func:`render_to_string()` and feed the result into an
  209. :class:`~django.http.HttpResponse` suitable for returning from a view.
  210. Finally, you can use configured engines directly:
  211. .. data:: engines
  212. Template engines are available in ``django.template.engines``::
  213. from django.template import engines
  214. django_engine = engines['django']
  215. template = django_engine.from_string("Hello {{ name }}!")
  216. The lookup key — ``'django'`` in this example — is the engine's
  217. :setting:`NAME <TEMPLATES-NAME>`.
  218. .. module:: django.template.backends
  219. Built-in backends
  220. -----------------
  221. .. module:: django.template.backends.django
  222. .. class:: DjangoTemplates
  223. Set :setting:`BACKEND <TEMPLATES-BACKEND>` to
  224. ``'django.template.backends.django.DjangoTemplates'`` to configure a Django
  225. template engine.
  226. When :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is ``True``, ``DjangoTemplates``
  227. engines look for templates in the ``templates`` subdirectory of installed
  228. applications. This generic name was kept for backwards-compatibility.
  229. ``DjangoTemplates`` engines accept the following :setting:`OPTIONS
  230. <TEMPLATES-OPTIONS>`:
  231. * ``'allowed_include_roots'``: a list of strings representing allowed prefixes
  232. for the ``{% ssi %}`` template tag. This is a security measure, so that
  233. template authors can't access files that they shouldn't be accessing.
  234. For example, if ``'allowed_include_roots'`` is ``['/home/html',
  235. '/var/www']``, then ``{% ssi /home/html/foo.txt %}`` would work, but ``{%
  236. ssi /etc/passwd %}`` wouldn't.
  237. It defaults to an empty list.
  238. .. deprecated:: 1.8
  239. ``allowed_include_roots`` is deprecated because the {% ssi %} tag is
  240. deprecated.
  241. * ``'context_processors'``: a list of dotted Python paths to callables that
  242. are used to populate the context when a template is rendered with a request.
  243. These callables take a request object as their argument and return a
  244. :class:`dict` of items to be merged into the context.
  245. It defaults to an empty list.
  246. See :class:`~django.template.RequestContext` for more information.
  247. * ``'debug'``: a boolean that turns on/off template debug mode. If it is
  248. ``True``, the fancy error page will display a detailed report for any
  249. exception raised during template rendering. This report contains the
  250. relevant snippet of the template with the appropriate line highlighted.
  251. It defaults to the value of the :setting:`DEBUG` setting.
  252. * ``'loaders'``: a list of dotted Python paths to template loader classes.
  253. Each ``Loader`` class knows how to import templates from a particular
  254. source. Optionally, a tuple can be used instead of a string. The first item
  255. in the tuple should be the ``Loader`` class name, and subsequent items are
  256. passed to the ``Loader`` during initialization.
  257. The default depends on the values of :setting:`DIRS <TEMPLATES-DIRS>` and
  258. :setting:`APP_DIRS <TEMPLATES-APP_DIRS>`.
  259. See :ref:`template-loaders` for details.
  260. * ``'string_if_invalid'``: the output, as a string, that the template system
  261. should use for invalid (e.g. misspelled) variables.
  262. It defaults to an empty string.
  263. See :ref:`invalid-template-variables` for details.
  264. * ``'file_charset'``: the charset used to read template files on disk.
  265. It defaults to the value of :setting:`FILE_CHARSET`.
  266. .. module:: django.template.backends.jinja2
  267. .. class:: Jinja2
  268. Requires Jinja2_ to be installed:
  269. .. code-block:: console
  270. $ pip install Jinja2
  271. Set :setting:`BACKEND <TEMPLATES-BACKEND>` to
  272. ``'django.template.backends.jinja2.Jinja2'`` to configure a Jinja2_ engine.
  273. When :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is ``True``, ``Jinja2`` engines
  274. look for templates in the ``jinja2`` subdirectory of installed applications.
  275. The most important entry in :setting:`OPTIONS <TEMPLATES-OPTIONS>` is
  276. ``'environment'``. It's a dotted Python path to a callable returning a Jinja2
  277. environment. It defaults to ``'jinja2.Environment'``. Django invokes that
  278. callable and passes other options as keyword arguments. Furthermore, Django
  279. adds defaults that differ from Jinja2's for a few options:
  280. * ``'autoescape'``: ``True``
  281. * ``'loader'``: a loader configured for :setting:`DIRS <TEMPLATES-DIRS>` and
  282. :setting:`APP_DIRS <TEMPLATES-APP_DIRS>`
  283. * ``'auto_reload'``: ``settings.DEBUG``
  284. * ``'undefined'``: ``DebugUndefined if settings.DEBUG else Undefined``
  285. The default configuration is purposefully kept to a minimum. The ``Jinja2``
  286. backend doesn't create a Django-flavored environment. It doesn't know about
  287. Django context processors, filters, and tags. In order to use Django-specific
  288. APIs, you must configure them into the environment.
  289. For example, you can create ``myproject/jinja2.py`` with this content::
  290. from django.contrib.staticfiles.storage import staticfiles_storage
  291. from django.core.urlresolvers import reverse
  292. from jinja2 import Environment
  293. def environment(**options):
  294. env = Environment(**options)
  295. env.globals.update({
  296. 'static': staticfiles_storage.url,
  297. 'url': reverse,
  298. })
  299. return env
  300. and set the ``'environment'`` option to ``'myproject.jinja2.environment'``.
  301. Then you could use the following constructs in Jinja2 templates:
  302. .. code-block:: html+jinja
  303. <img src="{{ static('path/to/company-logo.png') }}" alt="Company Logo">
  304. <a href="{{ url('admin:index') }}">Administration</a>
  305. The concepts of tags and filters exist both in the Django template language
  306. and in Jinja2 but they're used differently. Since Jinja2 supports passing
  307. arguments to callables in templates, many features that require a template tag
  308. or filter in Django templates can be achieved simply by calling a function in
  309. Jinja2 templates, as shown in the example above. Jinja2's global namespace
  310. removes the need for template context processors. The Django template language
  311. doesn't have an equivalent of Jinja2 tests.
  312. Custom backends
  313. ---------------
  314. Here's how to implement a custom template backend in order to use another
  315. template system. A template backend is a class that inherits
  316. ``django.template.backends.base.BaseEngine``. It must implement
  317. ``get_template()`` and optionally ``from_string()``. Here's an example for a
  318. fictional ``foobar`` template library::
  319. from django.template import TemplateDoesNotExist, TemplateSyntaxError
  320. from django.template.backends.base import BaseEngine
  321. from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
  322. import foobar
  323. class FooBar(BaseEngine):
  324. # Name of the subdirectory containing the templates for this engine
  325. # inside an installed application.
  326. app_dirname = 'foobar'
  327. def __init__(self, params):
  328. params = params.copy()
  329. options = params.pop('OPTIONS').copy()
  330. super(FooBar, self).__init__(params)
  331. self.engine = foobar.Engine(**options)
  332. def from_string(self, template_code):
  333. try:
  334. return Template(self.engine.from_string(template_code))
  335. except foobar.TemplateCompilationFailed as exc:
  336. raise TemplateSyntaxError(exc.args)
  337. def get_template(self, template_name):
  338. try:
  339. return Template(self.engine.get_template(template_name))
  340. except foobar.TemplateNotFound as exc:
  341. raise TemplateDoesNotExist(exc.args)
  342. except foobar.TemplateCompilationFailed as exc:
  343. raise TemplateSyntaxError(exc.args)
  344. class Template(object):
  345. def __init__(self, template):
  346. self.template = template
  347. def render(self, context=None, request=None):
  348. if context is None:
  349. context = {}
  350. if request is not None:
  351. context['request'] = request
  352. context['csrf_input'] = csrf_input_lazy(request)
  353. context['csrf_token'] = csrf_token_lazy(request)
  354. return self.template.render(context)
  355. See `DEP 182`_ for more information.
  356. .. currentmodule:: django.template
  357. .. _template-language-intro:
  358. The Django template language
  359. ============================
  360. .. highlightlang:: html+django
  361. Syntax
  362. ------
  363. .. admonition:: About this section
  364. This is an overview of the Django template language's syntax. For details
  365. see the :doc:`language syntax reference </ref/templates/language>`.
  366. A Django template is simply a text document or a Python string marked-up using
  367. the Django template language. Some constructs are recognized and interpreted
  368. by the template engine. The main ones are variables and tags.
  369. A template is rendered with a context. Rendering replaces variables with their
  370. values, which are looked up in the context, and executes tags. Everything else
  371. is output as is.
  372. The syntax of the Django template language involves four constructs.
  373. Variables
  374. ~~~~~~~~~
  375. A variable outputs a value from the context, which is a dict-like object
  376. mapping keys to values.
  377. Variables are surrounded by ``{{`` and ``}}`` like this::
  378. My first name is {{ first_name }}. My last name is {{ last_name }}.
  379. With a context of ``{'first_name': 'John', 'last_name': 'Doe'}``, this
  380. template renders to::
  381. My first name is John. My last name is Doe.
  382. Dictionary lookup, attribute lookup and list-index lookups are implemented
  383. with a dot notation::
  384. {{ my_dict.key }}
  385. {{ my_object.attribute }}
  386. {{ my_list.0 }}
  387. If a variable resolves to a callable, the template system will call it with no
  388. arguments and use its result instead of the callable.
  389. Tags
  390. ~~~~
  391. Tags provide arbitrary logic in the rendering process.
  392. This definition is deliberately vague. For example, a tag can output content,
  393. serve as a control structure e.g. an "if" statement or a "for" loop, grab
  394. content from a database, or even enable access to other template tags.
  395. Tags are surrounded by ``{%`` and ``%}`` like this::
  396. {% csrf_token %}
  397. Most tags accept arguments::
  398. {% cycle 'odd' 'even' %}
  399. Some tags require beginning and ending tags::
  400. {% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %}
  401. A :ref:`reference of built-in tags <ref-templates-builtins-tags>` is
  402. available as well as :ref:`instructions for writing custom tags
  403. <howto-writing-custom-template-tags>`.
  404. Filters
  405. ~~~~~~~
  406. Filters transform the values of variables and tag arguments.
  407. They look like this::
  408. {{ django|title }}
  409. With a context of ``{'django': 'the web framework for perfectionists with
  410. deadlines'}``, this template renders to::
  411. The Web Framework For Perfectionists With Deadlines
  412. Some filters take an argument::
  413. {{ my_date|date:"Y-m-d" }}
  414. A :ref:`reference of built-in filters <ref-templates-builtins-filters>` is
  415. available as well as :ref:`instructions for writing custom filters
  416. <howto-writing-custom-template-filters>`.
  417. Comments
  418. ~~~~~~~~
  419. Comments look like this::
  420. {# this won't be rendered #}
  421. A :ttag:`{% comment %} <comment>` tag provides multi-line comments.
  422. Components
  423. ----------
  424. .. admonition:: About this section
  425. This is an overview of the Django template language's APIs. For details
  426. see the :doc:`API reference </ref/templates/api>`.
  427. Engine
  428. ~~~~~~
  429. :class:`django.template.Engine` encapsulates an instance of the Django
  430. template system. The main reason for instantiating an
  431. :class:`~django.template.Engine` directly is to use the Django template
  432. language outside of a Django project.
  433. :class:`django.template.backends.django.DjangoTemplates` is a thin wrapper
  434. adapting :class:`django.template.Engine` to Django's template backend API.
  435. Template
  436. ~~~~~~~~
  437. :class:`django.template.Template` represents a compiled template.
  438. Templates are obtained with :meth:`Engine.get_template()
  439. <django.template.Engine.get_template>` or :meth:`Engine.from_string()
  440. <django.template.Engine.from_string>`
  441. Likewise ``django.template.backends.django.Template`` is a thin wrapper
  442. adapting :class:`django.template.Template` to the common template API.
  443. Context
  444. ~~~~~~~
  445. :class:`django.template.Context` holds some metadata in addition to the
  446. context data. It is passed to :meth:`Template.render()
  447. <django.template.Template.render>` for rendering a template.
  448. :class:`django.template.RequestContext` is a subclass of
  449. :class:`~django.template.Context` that stores the current
  450. :class:`~django.http.HttpRequest` and runs template context processors.
  451. The common API doesn't have an equivalent concept. Context data is passed in a
  452. plain :class:`dict` and the current :class:`~django.http.HttpRequest` is passed
  453. separately if needed.
  454. Loaders
  455. ~~~~~~~
  456. Template loaders are responsible for locating templates, loading them, and
  457. returning :class:`~django.template.Template` objects.
  458. Django provides several :ref:`built-in template loaders <template-loaders>`
  459. and supports :ref:`custom template loaders <custom-template-loaders>`.
  460. Context processors
  461. ~~~~~~~~~~~~~~~~~~
  462. Context processors are functions that receive the current
  463. :class:`~django.http.HttpRequest` as an argument and return a :class:`dict` of
  464. data to be added to the rendering context.
  465. Their main use is to add common data shared by all templates to the context
  466. without repeating code in every view.
  467. Django provides many :ref:`built-in context processors <context-processors>`.
  468. Implementing a custom context processor is as simple as defining a function.
  469. .. _Jinja2: http://jinja.pocoo.org/
  470. .. _DEP 182: https://github.com/django/deps/blob/master/accepted/0182-multiple-template-engines.rst