Debian Codegraph @

docs/topics/templates.txt

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