templates.txt 28 KB

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