templates.txt 29 KB

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