templates.txt 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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. .. warning::
  33. The template system isn't safe against untrusted template authors. For
  34. example, a site shouldn't allow its users to provide their own templates,
  35. since template authors can do things like perform XSS attacks and access
  36. properties of template variables that may contain sensitive information.
  37. .. _template-engines:
  38. Support for template engines
  39. ============================
  40. Configuration
  41. -------------
  42. Templates engines are configured with the :setting:`TEMPLATES` setting. It's a
  43. list of configurations, one for each engine. The default value is empty. The
  44. ``settings.py`` generated by the :djadmin:`startproject` command defines a
  45. more useful value::
  46. TEMPLATES = [
  47. {
  48. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  49. 'DIRS': [],
  50. 'APP_DIRS': True,
  51. 'OPTIONS': {
  52. # ... some options here ...
  53. },
  54. },
  55. ]
  56. :setting:`BACKEND <TEMPLATES-BACKEND>` is a dotted Python path to a template
  57. engine class implementing Django's template backend API. The built-in backends
  58. are :class:`django.template.backends.django.DjangoTemplates` and
  59. :class:`django.template.backends.jinja2.Jinja2`.
  60. Since most engines load templates from files, the top-level configuration for
  61. each engine contains two common settings:
  62. * :setting:`DIRS <TEMPLATES-DIRS>` defines a list of directories where the
  63. engine should look for template source files, in search order.
  64. * :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` tells whether the engine should
  65. look for templates inside installed applications. Each backend defines a
  66. conventional name for the subdirectory inside applications where its
  67. templates should be stored.
  68. While uncommon, it's possible to configure several instances of the same
  69. backend with different options. In that case you should define a unique
  70. :setting:`NAME <TEMPLATES-NAME>` for each engine.
  71. :setting:`OPTIONS <TEMPLATES-OPTIONS>` contains backend-specific settings.
  72. Usage
  73. -----
  74. .. _template-loading:
  75. .. module:: django.template.loader
  76. The ``django.template.loader`` module defines two functions to load templates.
  77. .. function:: get_template(template_name, using=None)
  78. This function loads the template with the given name and returns a
  79. ``Template`` object.
  80. The exact type of the return value depends on the backend that loaded the
  81. template. Each backend has its own ``Template`` class.
  82. ``get_template()`` tries each template engine in order until one succeeds.
  83. If the template cannot be found, it raises
  84. :exc:`~django.template.TemplateDoesNotExist`. If the template is found but
  85. contains invalid syntax, it raises
  86. :exc:`~django.template.TemplateSyntaxError`.
  87. How templates are searched and loaded depends on each engine's backend and
  88. configuration.
  89. If you want to restrict the search to a particular template engine, pass
  90. the engine's :setting:`NAME <TEMPLATES-NAME>` in the ``using`` argument.
  91. .. function:: select_template(template_name_list, using=None)
  92. ``select_template()`` is just like ``get_template()``, except it takes a
  93. list of template names. It tries each name in order and returns the first
  94. template that exists.
  95. .. currentmodule:: django.template
  96. If loading a template fails, the following two exceptions, defined in
  97. ``django.template``, may be raised:
  98. .. exception:: TemplateDoesNotExist(msg, tried=None, backend=None, chain=None)
  99. This exception is raised when a template cannot be found. It accepts the
  100. following optional arguments for populating the :ref:`template postmortem
  101. <template-postmortem>` on the debug page:
  102. ``backend``
  103. The template backend instance from which the exception originated.
  104. ``tried``
  105. A list of sources that were tried when finding the template. This is
  106. formatted as a list of tuples containing ``(origin, status)``, where
  107. ``origin`` is an :ref:`origin-like <template-origin-api>` object and
  108. ``status`` is a string with the reason the template wasn't found.
  109. ``chain``
  110. A list of intermediate :exc:`~django.template.TemplateDoesNotExist`
  111. exceptions raised when trying to load a template. This is used by
  112. functions, such as :func:`~django.template.loader.get_template`, that
  113. try to load a given template from multiple engines.
  114. .. exception:: TemplateSyntaxError(msg)
  115. This exception is raised when a template was found but contains errors.
  116. ``Template`` objects returned by ``get_template()`` and ``select_template()``
  117. must provide a ``render()`` method with the following signature:
  118. .. currentmodule:: django.template.backends.base
  119. .. method:: Template.render(context=None, request=None)
  120. Renders this template with a given context.
  121. If ``context`` is provided, it must be a :class:`dict`. If it isn't
  122. provided, the engine will render the template with an empty context.
  123. If ``request`` is provided, it must be an :class:`~django.http.HttpRequest`.
  124. Then the engine must make it, as well as the CSRF token, available in the
  125. template. How this is achieved is up to each backend.
  126. Here's an example of the search algorithm. For this example the
  127. :setting:`TEMPLATES` setting is::
  128. TEMPLATES = [
  129. {
  130. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  131. 'DIRS': [
  132. '/home/html/example.com',
  133. '/home/html/default',
  134. ],
  135. },
  136. {
  137. 'BACKEND': 'django.template.backends.jinja2.Jinja2',
  138. 'DIRS': [
  139. '/home/html/jinja2',
  140. ],
  141. },
  142. ]
  143. If you call ``get_template('story_detail.html')``, here are the files Django
  144. will look for, in order:
  145. * ``/home/html/example.com/story_detail.html`` (``'django'`` engine)
  146. * ``/home/html/default/story_detail.html`` (``'django'`` engine)
  147. * ``/home/html/jinja2/story_detail.html`` (``'jinja2'`` engine)
  148. If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
  149. here's what Django will look for:
  150. * ``/home/html/example.com/story_253_detail.html`` (``'django'`` engine)
  151. * ``/home/html/default/story_253_detail.html`` (``'django'`` engine)
  152. * ``/home/html/jinja2/story_253_detail.html`` (``'jinja2'`` engine)
  153. * ``/home/html/example.com/story_detail.html`` (``'django'`` engine)
  154. * ``/home/html/default/story_detail.html`` (``'django'`` engine)
  155. * ``/home/html/jinja2/story_detail.html`` (``'jinja2'`` engine)
  156. When Django finds a template that exists, it stops looking.
  157. .. admonition:: Tip
  158. You can use :func:`~django.template.loader.select_template()` for flexible
  159. template loading. For example, if you've written a news story and want
  160. some stories to have custom templates, use something like
  161. ``select_template(['story_%s_detail.html' % story.id,
  162. 'story_detail.html'])``. That'll allow you to use a custom template for an
  163. individual story, with a fallback template for stories that don't have
  164. custom templates.
  165. It's possible -- and preferable -- to organize templates in subdirectories
  166. inside each directory containing templates. The convention is to make a
  167. subdirectory for each Django app, with subdirectories within those
  168. subdirectories as needed.
  169. Do this for your own sanity. Storing all templates in the root level of a
  170. single directory gets messy.
  171. To load a template that's within a subdirectory, just use a slash, like so::
  172. get_template('news/story_detail.html')
  173. Using the same :setting:`TEMPLATES` option as above, this will attempt to load
  174. the following templates:
  175. * ``/home/html/example.com/news/story_detail.html`` (``'django'`` engine)
  176. * ``/home/html/default/news/story_detail.html`` (``'django'`` engine)
  177. * ``/home/html/jinja2/news/story_detail.html`` (``'jinja2'`` engine)
  178. .. currentmodule:: django.template.loader
  179. In addition, to cut down on the repetitive nature of loading and rendering
  180. templates, Django provides a shortcut function which automates the process.
  181. .. function:: render_to_string(template_name, context=None, request=None, using=None)
  182. ``render_to_string()`` loads a template like :func:`get_template` and
  183. calls its ``render()`` method immediately. It takes the following
  184. arguments.
  185. ``template_name``
  186. The name of the template to load and render. If it's a list of template
  187. names, Django uses :func:`select_template` instead of
  188. :func:`get_template` to find the template.
  189. ``context``
  190. A :class:`dict` to be used as the template's context for rendering.
  191. ``request``
  192. An optional :class:`~django.http.HttpRequest` that will be available
  193. during the template's rendering process.
  194. ``using``
  195. An optional template engine :setting:`NAME <TEMPLATES-NAME>`. The
  196. search for the template will be restricted to that engine.
  197. Usage example::
  198. from django.template.loader import render_to_string
  199. rendered = render_to_string('my_template.html', {'foo': 'bar'})
  200. See also the :func:`~django.shortcuts.render()` shortcut which calls
  201. :func:`render_to_string()` and feeds the result into an
  202. :class:`~django.http.HttpResponse` suitable for returning from a view.
  203. Finally, you can use configured engines directly:
  204. .. data:: engines
  205. Template engines are available in ``django.template.engines``::
  206. from django.template import engines
  207. django_engine = engines['django']
  208. template = django_engine.from_string("Hello {{ name }}!")
  209. The lookup key — ``'django'`` in this example — is the engine's
  210. :setting:`NAME <TEMPLATES-NAME>`.
  211. .. module:: django.template.backends
  212. Built-in backends
  213. -----------------
  214. .. module:: django.template.backends.django
  215. .. class:: DjangoTemplates
  216. Set :setting:`BACKEND <TEMPLATES-BACKEND>` to
  217. ``'django.template.backends.django.DjangoTemplates'`` to configure a Django
  218. template engine.
  219. When :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is ``True``, ``DjangoTemplates``
  220. engines look for templates in the ``templates`` subdirectory of installed
  221. applications. This generic name was kept for backwards-compatibility.
  222. ``DjangoTemplates`` engines accept the following :setting:`OPTIONS
  223. <TEMPLATES-OPTIONS>`:
  224. * ``'autoescape'``: a boolean that controls whether HTML autoescaping is
  225. enabled.
  226. It defaults to ``True``.
  227. .. warning::
  228. Only set it to ``False`` if you're rendering non-HTML templates!
  229. * ``'context_processors'``: a list of dotted Python paths to callables that
  230. are used to populate the context when a template is rendered with a request.
  231. These callables take a request object as their argument and return a
  232. :class:`dict` of items to be merged into the context.
  233. It defaults to an empty list.
  234. See :class:`~django.template.RequestContext` for more information.
  235. * ``'debug'``: a boolean that turns on/off template debug mode. If it is
  236. ``True``, the fancy error page will display a detailed report for any
  237. exception raised during template rendering. This report contains the
  238. relevant snippet of the template with the appropriate line highlighted.
  239. It defaults to the value of the :setting:`DEBUG` setting.
  240. * ``'loaders'``: a list of dotted Python paths to template loader classes.
  241. Each ``Loader`` class knows how to import templates from a particular
  242. source. Optionally, a tuple can be used instead of a string. The first item
  243. in the tuple should be the ``Loader`` class name, and subsequent items are
  244. passed to the ``Loader`` during initialization.
  245. The default depends on the values of :setting:`DIRS <TEMPLATES-DIRS>` and
  246. :setting:`APP_DIRS <TEMPLATES-APP_DIRS>`.
  247. See :ref:`template-loaders` for details.
  248. * ``'string_if_invalid'``: the output, as a string, that the template system
  249. should use for invalid (e.g. misspelled) variables.
  250. It defaults to an empty string.
  251. See :ref:`invalid-template-variables` for details.
  252. * ``'file_charset'``: the charset used to read template files on disk.
  253. It defaults to the value of :setting:`FILE_CHARSET`.
  254. * ``'libraries'``: A dictionary of labels and dotted Python paths of template
  255. tag modules to register with the template engine. This can be used to add
  256. new libraries or provide alternate labels for existing ones. For example::
  257. OPTIONS={
  258. 'libraries': {
  259. 'myapp_tags': 'path.to.myapp.tags',
  260. 'admin.urls': 'django.contrib.admin.templatetags.admin_urls',
  261. },
  262. }
  263. Libraries can be loaded by passing the corresponding dictionary key to
  264. the :ttag:`{% load %}<load>` tag.
  265. * ``'builtins'``: A list of dotted Python paths of template tag modules to
  266. add to :doc:`built-ins </ref/templates/builtins>`. For example::
  267. OPTIONS={
  268. 'builtins': ['myapp.builtins'],
  269. }
  270. Tags and filters from built-in libraries can be used without first calling
  271. the :ttag:`{% load %} <load>` tag.
  272. .. module:: django.template.backends.jinja2
  273. .. class:: Jinja2
  274. Requires Jinja2_ to be installed:
  275. .. code-block:: console
  276. $ pip install Jinja2
  277. Set :setting:`BACKEND <TEMPLATES-BACKEND>` to
  278. ``'django.template.backends.jinja2.Jinja2'`` to configure a Jinja2_ engine.
  279. When :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is ``True``, ``Jinja2`` engines
  280. look for templates in the ``jinja2`` subdirectory of installed applications.
  281. The most important entry in :setting:`OPTIONS <TEMPLATES-OPTIONS>` is
  282. ``'environment'``. It's a dotted Python path to a callable returning a Jinja2
  283. environment. It defaults to ``'jinja2.Environment'``. Django invokes that
  284. callable and passes other options as keyword arguments. Furthermore, Django
  285. adds defaults that differ from Jinja2's for a few options:
  286. * ``'autoescape'``: ``True``
  287. * ``'loader'``: a loader configured for :setting:`DIRS <TEMPLATES-DIRS>` and
  288. :setting:`APP_DIRS <TEMPLATES-APP_DIRS>`
  289. * ``'auto_reload'``: ``settings.DEBUG``
  290. * ``'undefined'``: ``DebugUndefined if settings.DEBUG else Undefined``
  291. ``Jinja2`` engines also accept the following :setting:`OPTIONS
  292. <TEMPLATES-OPTIONS>`:
  293. * ``'context_processors'``: a list of dotted Python paths to callables that
  294. are used to populate the context when a template is rendered with a request.
  295. These callables take a request object as their argument and return a
  296. :class:`dict` of items to be merged into the context.
  297. It defaults to an empty list.
  298. .. versionadded:: 1.11
  299. The ``'context_processors'`` option was added.
  300. The default configuration is purposefully kept to a minimum. If a template is
  301. rendered with a request (e.g. when using :py:func:`~django.shortcuts.render`),
  302. the ``Jinja2`` backend adds the globals ``request``, ``csrf_input``, and
  303. ``csrf_token`` to the context. Apart from that, this backend doesn't create a
  304. Django-flavored environment. It doesn't know about Django filters and tags.
  305. In order to use Django-specific APIs, you must configure them into the
  306. environment.
  307. For example, you can create ``myproject/jinja2.py`` with this content::
  308. from django.contrib.staticfiles.storage import staticfiles_storage
  309. from django.urls import reverse
  310. from jinja2 import Environment
  311. def environment(**options):
  312. env = Environment(**options)
  313. env.globals.update({
  314. 'static': staticfiles_storage.url,
  315. 'url': reverse,
  316. })
  317. return env
  318. and set the ``'environment'`` option to ``'myproject.jinja2.environment'``.
  319. Then you could use the following constructs in Jinja2 templates:
  320. .. code-block:: html+jinja
  321. <img src="{{ static('path/to/company-logo.png') }}" alt="Company Logo">
  322. <a href="{{ url('admin:index') }}">Administration</a>
  323. The concepts of tags and filters exist both in the Django template language
  324. and in Jinja2 but they're used differently. Since Jinja2 supports passing
  325. arguments to callables in templates, many features that require a template tag
  326. or filter in Django templates can be achieved simply by calling a function in
  327. Jinja2 templates, as shown in the example above. Jinja2's global namespace
  328. removes the need for template context processors. The Django template language
  329. doesn't have an equivalent of Jinja2 tests.
  330. Custom backends
  331. ---------------
  332. Here's how to implement a custom template backend in order to use another
  333. template system. A template backend is a class that inherits
  334. ``django.template.backends.base.BaseEngine``. It must implement
  335. ``get_template()`` and optionally ``from_string()``. Here's an example for a
  336. fictional ``foobar`` template library::
  337. from django.template import TemplateDoesNotExist, TemplateSyntaxError
  338. from django.template.backends.base import BaseEngine
  339. from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
  340. import foobar
  341. class FooBar(BaseEngine):
  342. # Name of the subdirectory containing the templates for this engine
  343. # inside an installed application.
  344. app_dirname = 'foobar'
  345. def __init__(self, params):
  346. params = params.copy()
  347. options = params.pop('OPTIONS').copy()
  348. super().__init__(params)
  349. self.engine = foobar.Engine(**options)
  350. def from_string(self, template_code):
  351. try:
  352. return Template(self.engine.from_string(template_code))
  353. except foobar.TemplateCompilationFailed as exc:
  354. raise TemplateSyntaxError(exc.args)
  355. def get_template(self, template_name):
  356. try:
  357. return Template(self.engine.get_template(template_name))
  358. except foobar.TemplateNotFound as exc:
  359. raise TemplateDoesNotExist(exc.args, backend=self)
  360. except foobar.TemplateCompilationFailed as exc:
  361. raise TemplateSyntaxError(exc.args)
  362. class Template(object):
  363. def __init__(self, template):
  364. self.template = template
  365. def render(self, context=None, request=None):
  366. if context is None:
  367. context = {}
  368. if request is not None:
  369. context['request'] = request
  370. context['csrf_input'] = csrf_input_lazy(request)
  371. context['csrf_token'] = csrf_token_lazy(request)
  372. return self.template.render(context)
  373. See `DEP 182`_ for more information.
  374. .. _template-debug-integration:
  375. Debug integration for custom engines
  376. ------------------------------------
  377. The Django debug page has hooks to provide detailed information when a template
  378. error arises. Custom template engines can use these hooks to enhance the
  379. traceback information that appears to users. The following hooks are available:
  380. .. _template-postmortem:
  381. Template postmortem
  382. ~~~~~~~~~~~~~~~~~~~
  383. The postmortem appears when :exc:`~django.template.TemplateDoesNotExist` is
  384. raised. It lists the template engines and loaders that were used when trying
  385. to find a given template. For example, if two Django engines are configured,
  386. the postmortem will appear like:
  387. .. image:: _images/postmortem.png
  388. Custom engines can populate the postmortem by passing the ``backend`` and
  389. ``tried`` arguments when raising :exc:`~django.template.TemplateDoesNotExist`.
  390. Backends that use the postmortem :ref:`should specify an origin
  391. <template-origin-api>` on the template object.
  392. Contextual line information
  393. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  394. If an error happens during template parsing or rendering, Django can display
  395. the line the error happened on. For example:
  396. .. image:: _images/template-lines.png
  397. Custom engines can populate this information by setting a ``template_debug``
  398. attribute on exceptions raised during parsing and rendering. This attribute
  399. is a :class:`dict` with the following values:
  400. * ``'name'``: The name of the template in which the exception occurred.
  401. * ``'message'``: The exception message.
  402. * ``'source_lines'``: The lines before, after, and including the line the
  403. exception occurred on. This is for context, so it shouldn't contain more than
  404. 20 lines or so.
  405. * ``'line'``: The line number on which the exception occurred.
  406. * ``'before'``: The content on the error line before the token that raised the
  407. error.
  408. * ``'during'``: The token that raised the error.
  409. * ``'after'``: The content on the error line after the token that raised the
  410. error.
  411. * ``'total'``: The number of lines in ``source_lines``.
  412. * ``'top'``: The line number where ``source_lines`` starts.
  413. * ``'bottom'``: The line number where ``source_lines`` ends.
  414. Given the above template error, ``template_debug`` would look like::
  415. {
  416. 'name': '/path/to/template.html',
  417. 'message': "Invalid block tag: 'syntax'",
  418. 'source_lines': [
  419. (1, 'some\n'),
  420. (2, 'lines\n'),
  421. (3, 'before\n'),
  422. (4, 'Hello {% syntax error %} {{ world }}\n'),
  423. (5, 'some\n'),
  424. (6, 'lines\n'),
  425. (7, 'after\n'),
  426. (8, ''),
  427. ],
  428. 'line': 4,
  429. 'before': 'Hello ',
  430. 'during': '{% syntax error %}',
  431. 'after': ' {{ world }}\n',
  432. 'total': 9,
  433. 'bottom': 9,
  434. 'top': 1,
  435. }
  436. .. _template-origin-api:
  437. Origin API and 3rd-party integration
  438. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  439. Django templates have an :class:`~django.template.base.Origin` object available
  440. through the ``template.origin`` attribute. This enables debug information to be
  441. displayed in the :ref:`template postmortem <template-postmortem>`, as well as
  442. in 3rd-party libraries, like the `Django Debug Toolbar`_.
  443. Custom engines can provide their own ``template.origin`` information by
  444. creating an object that specifies the following attributes:
  445. * ``'name'``: The full path to the template.
  446. * ``'template_name'``: The relative path to the template as passed into the
  447. the template loading methods.
  448. * ``'loader_name'``: An optional string identifying the function or class used
  449. to load the template, e.g. ``django.template.loaders.filesystem.Loader``.
  450. .. currentmodule:: django.template
  451. .. _template-language-intro:
  452. The Django template language
  453. ============================
  454. .. highlightlang:: html+django
  455. Syntax
  456. ------
  457. .. admonition:: About this section
  458. This is an overview of the Django template language's syntax. For details
  459. see the :doc:`language syntax reference </ref/templates/language>`.
  460. A Django template is simply a text document or a Python string marked-up using
  461. the Django template language. Some constructs are recognized and interpreted
  462. by the template engine. The main ones are variables and tags.
  463. A template is rendered with a context. Rendering replaces variables with their
  464. values, which are looked up in the context, and executes tags. Everything else
  465. is output as is.
  466. The syntax of the Django template language involves four constructs.
  467. Variables
  468. ~~~~~~~~~
  469. A variable outputs a value from the context, which is a dict-like object
  470. mapping keys to values.
  471. Variables are surrounded by ``{{`` and ``}}`` like this::
  472. My first name is {{ first_name }}. My last name is {{ last_name }}.
  473. With a context of ``{'first_name': 'John', 'last_name': 'Doe'}``, this
  474. template renders to::
  475. My first name is John. My last name is Doe.
  476. Dictionary lookup, attribute lookup and list-index lookups are implemented
  477. with a dot notation::
  478. {{ my_dict.key }}
  479. {{ my_object.attribute }}
  480. {{ my_list.0 }}
  481. If a variable resolves to a callable, the template system will call it with no
  482. arguments and use its result instead of the callable.
  483. Tags
  484. ~~~~
  485. Tags provide arbitrary logic in the rendering process.
  486. This definition is deliberately vague. For example, a tag can output content,
  487. serve as a control structure e.g. an "if" statement or a "for" loop, grab
  488. content from a database, or even enable access to other template tags.
  489. Tags are surrounded by ``{%`` and ``%}`` like this::
  490. {% csrf_token %}
  491. Most tags accept arguments::
  492. {% cycle 'odd' 'even' %}
  493. Some tags require beginning and ending tags::
  494. {% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %}
  495. A :ref:`reference of built-in tags <ref-templates-builtins-tags>` is
  496. available as well as :ref:`instructions for writing custom tags
  497. <howto-writing-custom-template-tags>`.
  498. Filters
  499. ~~~~~~~
  500. Filters transform the values of variables and tag arguments.
  501. They look like this::
  502. {{ django|title }}
  503. With a context of ``{'django': 'the web framework for perfectionists with
  504. deadlines'}``, this template renders to::
  505. The Web Framework For Perfectionists With Deadlines
  506. Some filters take an argument::
  507. {{ my_date|date:"Y-m-d" }}
  508. A :ref:`reference of built-in filters <ref-templates-builtins-filters>` is
  509. available as well as :ref:`instructions for writing custom filters
  510. <howto-writing-custom-template-filters>`.
  511. Comments
  512. ~~~~~~~~
  513. Comments look like this::
  514. {# this won't be rendered #}
  515. A :ttag:`{% comment %} <comment>` tag provides multi-line comments.
  516. Components
  517. ----------
  518. .. admonition:: About this section
  519. This is an overview of the Django template language's APIs. For details
  520. see the :doc:`API reference </ref/templates/api>`.
  521. Engine
  522. ~~~~~~
  523. :class:`django.template.Engine` encapsulates an instance of the Django
  524. template system. The main reason for instantiating an
  525. :class:`~django.template.Engine` directly is to use the Django template
  526. language outside of a Django project.
  527. :class:`django.template.backends.django.DjangoTemplates` is a thin wrapper
  528. adapting :class:`django.template.Engine` to Django's template backend API.
  529. Template
  530. ~~~~~~~~
  531. :class:`django.template.Template` represents a compiled template.
  532. Templates are obtained with :meth:`Engine.get_template()
  533. <django.template.Engine.get_template>` or :meth:`Engine.from_string()
  534. <django.template.Engine.from_string>`
  535. Likewise ``django.template.backends.django.Template`` is a thin wrapper
  536. adapting :class:`django.template.Template` to the common template API.
  537. Context
  538. ~~~~~~~
  539. :class:`django.template.Context` holds some metadata in addition to the
  540. context data. It is passed to :meth:`Template.render()
  541. <django.template.Template.render>` for rendering a template.
  542. :class:`django.template.RequestContext` is a subclass of
  543. :class:`~django.template.Context` that stores the current
  544. :class:`~django.http.HttpRequest` and runs template context processors.
  545. The common API doesn't have an equivalent concept. Context data is passed in a
  546. plain :class:`dict` and the current :class:`~django.http.HttpRequest` is passed
  547. separately if needed.
  548. Loaders
  549. ~~~~~~~
  550. Template loaders are responsible for locating templates, loading them, and
  551. returning :class:`~django.template.Template` objects.
  552. Django provides several :ref:`built-in template loaders <template-loaders>`
  553. and supports :ref:`custom template loaders <custom-template-loaders>`.
  554. Context processors
  555. ~~~~~~~~~~~~~~~~~~
  556. Context processors are functions that receive the current
  557. :class:`~django.http.HttpRequest` as an argument and return a :class:`dict` of
  558. data to be added to the rendering context.
  559. Their main use is to add common data shared by all templates to the context
  560. without repeating code in every view.
  561. Django provides many :ref:`built-in context processors <context-processors>`.
  562. Implementing a custom context processor is as simple as defining a function.
  563. .. _Jinja2: http://jinja.pocoo.org/
  564. .. _DEP 182: https://github.com/django/deps/blob/master/final/0182-multiple-template-engines.rst
  565. .. _Django Debug Toolbar: https://github.com/django-debug-toolbar/django-debug-toolbar