| 1 |
============================ |
| 2 |
The Django template language |
| 3 |
============================ |
| 4 |
|
| 5 |
This document explains the language syntax of the Django template system. If |
| 6 |
you're looking for a more technical perspective on how it works and how to |
| 7 |
extend it, see :doc:`/ref/templates/api`. |
| 8 |
|
| 9 |
Django's template language is designed to strike a balance between power and |
| 10 |
ease. It's designed to feel comfortable to those used to working with HTML. If |
| 11 |
you have any exposure to other text-based template languages, such as Smarty_ |
| 12 |
or Jinja2_, you should feel right at home with Django's templates. |
| 13 |
|
| 14 |
.. admonition:: Philosophy |
| 15 |
|
| 16 |
If you have a background in programming, or if you're used to languages |
| 17 |
which mix programming code directly into HTML, you'll want to bear in |
| 18 |
mind that the Django template system is not simply Python embedded into |
| 19 |
HTML. This is by design: the template system is meant to express |
| 20 |
presentation, not program logic. |
| 21 |
|
| 22 |
The Django template system provides tags which function similarly to some |
| 23 |
programming constructs -- an :ttag:`if` tag for boolean tests, a :ttag:`for` |
| 24 |
tag for looping, etc. -- but these are not simply executed as the |
| 25 |
corresponding Python code, and the template system will not execute |
| 26 |
arbitrary Python expressions. Only the tags, filters and syntax listed below |
| 27 |
are supported by default (although you can add :doc:`your own extensions |
| 28 |
</howto/custom-template-tags>` to the template language as needed). |
| 29 |
|
| 30 |
.. _`The Django template language: For Python programmers`: ../templates_python/ |
| 31 |
.. _Smarty: https://www.smarty.net/ |
| 32 |
.. _Jinja2: https://palletsprojects.com/p/jinja/ |
| 33 |
|
| 34 |
Templates |
| 35 |
========= |
| 36 |
|
| 37 |
A template is a text file. It can generate any text-based format (HTML, XML, |
| 38 |
CSV, etc.). |
| 39 |
|
| 40 |
A template contains **variables**, which get replaced with values when the |
| 41 |
template is evaluated, and **tags**, which control the logic of the template. |
| 42 |
|
| 43 |
Below is a minimal template that illustrates a few basics. Each element will be |
| 44 |
explained later in this document. |
| 45 |
|
| 46 |
.. code-block:: html+django |
| 47 |
|
| 48 |
{% extends "base_generic.html" %} |
| 49 |
|
| 50 |
{% block title %}{{ section.title }}{% endblock %} |
| 51 |
|
| 52 |
{% block content %} |
| 53 |
<h1>{{ section.title }}</h1> |
| 54 |
|
| 55 |
{% for story in story_list %} |
| 56 |
<h2> |
| 57 |
<a href="{{ story.get_absolute_url }}"> |
| 58 |
{{ story.headline|upper }} |
| 59 |
</a> |
| 60 |
</h2> |
| 61 |
<p>{{ story.tease|truncatewords:"100" }}</p> |
| 62 |
{% endfor %} |
| 63 |
{% endblock %} |
| 64 |
|
| 65 |
.. admonition:: Philosophy |
| 66 |
|
| 67 |
Why use a text-based template instead of an XML-based one (like Zope's |
| 68 |
TAL)? We wanted Django's template language to be usable for more than |
| 69 |
just XML/HTML templates. You can use the template language for any |
| 70 |
text-based format such as emails, JavaScript and CSV. |
| 71 |
|
| 72 |
.. _template-variables: |
| 73 |
|
| 74 |
Variables |
| 75 |
========= |
| 76 |
|
| 77 |
Variables look like this: ``{{ variable }}``. When the template engine |
| 78 |
encounters a variable, it evaluates that variable and replaces it with the |
| 79 |
result. Variable names consist of any combination of alphanumeric characters |
| 80 |
and the underscore (``"_"``) but may not start with an underscore, and may not |
| 81 |
be a number. The dot (``"."``) also appears in variable sections, although that |
| 82 |
has a special meaning, as indicated below. Importantly, *you cannot have spaces |
| 83 |
or punctuation characters in variable names.* |
| 84 |
|
| 85 |
Use a dot (``.``) to access attributes of a variable. |
| 86 |
|
| 87 |
.. admonition:: Behind the scenes |
| 88 |
|
| 89 |
Technically, when the template system encounters a dot, it tries the |
| 90 |
following lookups, in this order: |
| 91 |
|
| 92 |
* Dictionary lookup |
| 93 |
* Attribute or method lookup |
| 94 |
* Numeric index lookup |
| 95 |
|
| 96 |
If the resulting value is callable, it is called with no arguments. The |
| 97 |
result of the call becomes the template value. |
| 98 |
|
| 99 |
This lookup order can cause some unexpected behavior with objects that |
| 100 |
override dictionary lookup. For example, consider the following code snippet |
| 101 |
that attempts to loop over a ``collections.defaultdict``: |
| 102 |
|
| 103 |
.. code-block:: html+django |
| 104 |
|
| 105 |
{% for k, v in defaultdict.items %} |
| 106 |
Do something with k and v here... |
| 107 |
{% endfor %} |
| 108 |
|
| 109 |
Because dictionary lookup happens first, that behavior kicks in and provides |
| 110 |
a default value instead of using the intended ``.items()`` method. In this |
| 111 |
case, consider converting to a dictionary first. |
| 112 |
|
| 113 |
In the above example, ``{{ section.title }}`` will be replaced with the |
| 114 |
``title`` attribute of the ``section`` object. |
| 115 |
|
| 116 |
If you use a variable that doesn't exist, the template system will insert the |
| 117 |
value of the ``string_if_invalid`` option, which is set to ``''`` (the empty |
| 118 |
string) by default. |
| 119 |
|
| 120 |
Note that "bar" in a template expression like ``{{ foo.bar }}`` will be |
| 121 |
interpreted as a literal string and not using the value of the variable "bar", |
| 122 |
if one exists in the template context. |
| 123 |
|
| 124 |
Variable attributes that begin with an underscore may not be accessed as |
| 125 |
they're generally considered private. |
| 126 |
|
| 127 |
Filters |
| 128 |
======= |
| 129 |
|
| 130 |
You can modify variables for display by using **filters**. |
| 131 |
|
| 132 |
Filters look like this: ``{{ name|lower }}``. This displays the value of the |
| 133 |
``{{ name }}`` variable after being filtered through the :tfilter:`lower` |
| 134 |
filter, which converts text to lowercase. Use a pipe (``|``) to apply a filter. |
| 135 |
|
| 136 |
Filters can be "chained." The output of one filter is applied to the next. |
| 137 |
``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents, |
| 138 |
then converting line breaks to ``<p>`` tags. |
| 139 |
|
| 140 |
Some filters take arguments. A filter argument looks like this: ``{{ |
| 141 |
bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio`` |
| 142 |
variable. |
| 143 |
|
| 144 |
Filter arguments that contain spaces must be quoted; for example, to join a |
| 145 |
list with commas and spaces you'd use ``{{ list|join:", " }}``. |
| 146 |
|
| 147 |
Django provides about sixty built-in template filters. You can read all about |
| 148 |
them in the :ref:`built-in filter reference <ref-templates-builtins-filters>`. |
| 149 |
To give you a taste of what's available, here are some of the more commonly |
| 150 |
used template filters: |
| 151 |
|
| 152 |
:tfilter:`default` |
| 153 |
If a variable is false or empty, use given default. Otherwise, use the |
| 154 |
value of the variable. For example: |
| 155 |
|
| 156 |
.. code-block:: html+django |
| 157 |
|
| 158 |
{{ value|default:"nothing" }} |
| 159 |
|
| 160 |
If ``value`` isn't provided or is empty, the above will display |
| 161 |
"``nothing``". |
| 162 |
|
| 163 |
:tfilter:`length` |
| 164 |
Returns the length of the value. This works for both strings and lists. |
| 165 |
For example: |
| 166 |
|
| 167 |
.. code-block:: html+django |
| 168 |
|
| 169 |
{{ value|length }} |
| 170 |
|
| 171 |
If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``. |
| 172 |
|
| 173 |
:tfilter:`filesizeformat` |
| 174 |
Formats the value like a "human-readable" file size (i.e. ``'13 KB'``, |
| 175 |
``'4.1 MB'``, ``'102 bytes'``, etc.). For example: |
| 176 |
|
| 177 |
.. code-block:: html+django |
| 178 |
|
| 179 |
{{ value|filesizeformat }} |
| 180 |
|
| 181 |
If ``value`` is 123456789, the output would be ``117.7 MB``. |
| 182 |
|
| 183 |
Again, these are just a few examples; see the :ref:`built-in filter reference |
| 184 |
<ref-templates-builtins-filters>` for the complete list. |
| 185 |
|
| 186 |
You can also create your own custom template filters; see |
| 187 |
:doc:`/howto/custom-template-tags`. |
| 188 |
|
| 189 |
.. seealso:: |
| 190 |
|
| 191 |
Django's admin interface can include a complete reference of all template |
| 192 |
tags and filters available for a given site. See |
| 193 |
:doc:`/ref/contrib/admin/admindocs`. |
| 194 |
|
| 195 |
Tags |
| 196 |
==== |
| 197 |
|
| 198 |
Tags look like this: ``{% tag %}``. Tags are more complex than variables: Some |
| 199 |
create text in the output, some control flow by performing loops or logic, and |
| 200 |
some load external information into the template to be used by later variables. |
| 201 |
|
| 202 |
Some tags require beginning and ending tags (i.e. ``{% tag %} ... tag contents |
| 203 |
... {% endtag %}``). |
| 204 |
|
| 205 |
Django ships with about two dozen built-in template tags. You can read all about |
| 206 |
them in the :ref:`built-in tag reference <ref-templates-builtins-tags>`. To give |
| 207 |
you a taste of what's available, here are some of the more commonly used |
| 208 |
tags: |
| 209 |
|
| 210 |
:ttag:`for` |
| 211 |
Loop over each item in an array. For example, to display a list of athletes |
| 212 |
provided in ``athlete_list``: |
| 213 |
|
| 214 |
.. code-block:: html+django |
| 215 |
|
| 216 |
<ul> |
| 217 |
{% for athlete in athlete_list %} |
| 218 |
<li>{{ athlete.name }}</li> |
| 219 |
{% endfor %} |
| 220 |
</ul> |
| 221 |
|
| 222 |
:ttag:`if`, ``elif``, and ``else`` |
| 223 |
Evaluates a variable, and if that variable is "true" the contents of the |
| 224 |
block are displayed: |
| 225 |
|
| 226 |
.. code-block:: html+django |
| 227 |
|
| 228 |
{% if athlete_list %} |
| 229 |
Number of athletes: {{ athlete_list|length }} |
| 230 |
{% elif athlete_in_locker_room_list %} |
| 231 |
Athletes should be out of the locker room soon! |
| 232 |
{% else %} |
| 233 |
No athletes. |
| 234 |
{% endif %} |
| 235 |
|
| 236 |
In the above, if ``athlete_list`` is not empty, the number of athletes |
| 237 |
will be displayed by the ``{{ athlete_list|length }}`` variable. Otherwise, |
| 238 |
if ``athlete_in_locker_room_list`` is not empty, the message "Athletes |
| 239 |
should be out..." will be displayed. If both lists are empty, |
| 240 |
"No athletes." will be displayed. |
| 241 |
|
| 242 |
You can also use filters and various operators in the :ttag:`if` tag: |
| 243 |
|
| 244 |
.. code-block:: html+django |
| 245 |
|
| 246 |
{% if athlete_list|length > 1 %} |
| 247 |
Team: {% for athlete in athlete_list %} ... {% endfor %} |
| 248 |
{% else %} |
| 249 |
Athlete: {{ athlete_list.0.name }} |
| 250 |
{% endif %} |
| 251 |
|
| 252 |
While the above example works, be aware that most template filters return |
| 253 |
strings, so mathematical comparisons using filters will generally not work |
| 254 |
as you expect. :tfilter:`length` is an exception. |
| 255 |
|
| 256 |
:ttag:`block` and :ttag:`extends` |
| 257 |
Set up `template inheritance`_ (see below), a powerful way |
| 258 |
of cutting down on "boilerplate" in templates. |
| 259 |
|
| 260 |
Again, the above is only a selection of the whole list; see the :ref:`built-in |
| 261 |
tag reference <ref-templates-builtins-tags>` for the complete list. |
| 262 |
|
| 263 |
You can also create your own custom template tags; see |
| 264 |
:doc:`/howto/custom-template-tags`. |
| 265 |
|
| 266 |
.. seealso:: |
| 267 |
|
| 268 |
Django's admin interface can include a complete reference of all template |
| 269 |
tags and filters available for a given site. See |
| 270 |
:doc:`/ref/contrib/admin/admindocs`. |
| 271 |
|
| 272 |
.. _template-comments: |
| 273 |
|
| 274 |
Comments |
| 275 |
======== |
| 276 |
|
| 277 |
To comment-out part of a line in a template, use the comment syntax: ``{# #}``. |
| 278 |
|
| 279 |
For example, this template would render as ``'hello'``: |
| 280 |
|
| 281 |
.. code-block:: html+django |
| 282 |
|
| 283 |
{# greeting #}hello |
| 284 |
|
| 285 |
A comment can contain any template code, invalid or not. For example: |
| 286 |
|
| 287 |
.. code-block:: html+django |
| 288 |
|
| 289 |
{# {% if foo %}bar{% else %} #} |
| 290 |
|
| 291 |
This syntax can only be used for single-line comments (no newlines are permitted |
| 292 |
between the ``{#`` and ``#}`` delimiters). If you need to comment out a |
| 293 |
multiline portion of the template, see the :ttag:`comment` tag. |
| 294 |
|
| 295 |
.. _template-inheritance: |
| 296 |
|
| 297 |
Template inheritance |
| 298 |
==================== |
| 299 |
|
| 300 |
The most powerful -- and thus the most complex -- part of Django's template |
| 301 |
engine is template inheritance. Template inheritance allows you to build a base |
| 302 |
"skeleton" template that contains all the common elements of your site and |
| 303 |
defines **blocks** that child templates can override. |
| 304 |
|
| 305 |
Let's look at template inheritance by starting with an example: |
| 306 |
|
| 307 |
.. code-block:: html+django |
| 308 |
|
| 309 |
<!DOCTYPE html> |
| 310 |
<html lang="en"> |
| 311 |
<head> |
| 312 |
<link rel="stylesheet" href="style.css"> |
| 313 |
<title>{% block title %}My amazing site{% endblock %}</title> |
| 314 |
</head> |
| 315 |
|
| 316 |
<body> |
| 317 |
<div id="sidebar"> |
| 318 |
{% block sidebar %} |
| 319 |
<ul> |
| 320 |
<li><a href="/">Home</a></li> |
| 321 |
<li><a href="/blog/">Blog</a></li> |
| 322 |
</ul> |
| 323 |
{% endblock %} |
| 324 |
</div> |
| 325 |
|
| 326 |
<div id="content"> |
| 327 |
{% block content %}{% endblock %} |
| 328 |
</div> |
| 329 |
</body> |
| 330 |
</html> |
| 331 |
|
| 332 |
This template, which we'll call ``base.html``, defines an HTML skeleton |
| 333 |
document that you might use for a two-column page. It's the job of "child" |
| 334 |
templates to fill the empty blocks with content. |
| 335 |
|
| 336 |
In this example, the :ttag:`block` tag defines three blocks that child |
| 337 |
templates can fill in. All the :ttag:`block` tag does is to tell the template |
| 338 |
engine that a child template may override those portions of the template. |
| 339 |
|
| 340 |
A child template might look like this: |
| 341 |
|
| 342 |
.. code-block:: html+django |
| 343 |
|
| 344 |
{% extends "base.html" %} |
| 345 |
|
| 346 |
{% block title %}My amazing blog{% endblock %} |
| 347 |
|
| 348 |
{% block content %} |
| 349 |
{% for entry in blog_entries %} |
| 350 |
<h2>{{ entry.title }}</h2> |
| 351 |
<p>{{ entry.body }}</p> |
| 352 |
{% endfor %} |
| 353 |
{% endblock %} |
| 354 |
|
| 355 |
The :ttag:`extends` tag is the key here. It tells the template engine that |
| 356 |
this template "extends" another template. When the template system evaluates |
| 357 |
this template, first it locates the parent -- in this case, "base.html". |
| 358 |
|
| 359 |
At that point, the template engine will notice the three :ttag:`block` tags |
| 360 |
in ``base.html`` and replace those blocks with the contents of the child |
| 361 |
template. Depending on the value of ``blog_entries``, the output might look |
| 362 |
like: |
| 363 |
|
| 364 |
.. code-block:: html+django |
| 365 |
|
| 366 |
<!DOCTYPE html> |
| 367 |
<html lang="en"> |
| 368 |
<head> |
| 369 |
<link rel="stylesheet" href="style.css"> |
| 370 |
<title>My amazing blog</title> |
| 371 |
</head> |
| 372 |
|
| 373 |
<body> |
| 374 |
<div id="sidebar"> |
| 375 |
<ul> |
| 376 |
<li><a href="/">Home</a></li> |
| 377 |
<li><a href="/blog/">Blog</a></li> |
| 378 |
</ul> |
| 379 |
</div> |
| 380 |
|
| 381 |
<div id="content"> |
| 382 |
<h2>Entry one</h2> |
| 383 |
<p>This is my first entry.</p> |
| 384 |
|
| 385 |
<h2>Entry two</h2> |
| 386 |
<p>This is my second entry.</p> |
| 387 |
</div> |
| 388 |
</body> |
| 389 |
</html> |
| 390 |
|
| 391 |
Note that since the child template didn't define the ``sidebar`` block, the |
| 392 |
value from the parent template is used instead. Content within a ``{% block %}`` |
| 393 |
tag in a parent template is always used as a fallback. |
| 394 |
|
| 395 |
You can use as many levels of inheritance as needed. One common way of using |
| 396 |
inheritance is the following three-level approach: |
| 397 |
|
| 398 |
* Create a ``base.html`` template that holds the main look-and-feel of your |
| 399 |
site. |
| 400 |
* Create a ``base_SECTIONNAME.html`` template for each "section" of your |
| 401 |
site. For example, ``base_news.html``, ``base_sports.html``. These |
| 402 |
templates all extend ``base.html`` and include section-specific |
| 403 |
styles/design. |
| 404 |
* Create individual templates for each type of page, such as a news |
| 405 |
article or blog entry. These templates extend the appropriate section |
| 406 |
template. |
| 407 |
|
| 408 |
This approach maximizes code reuse and helps to add items to shared content |
| 409 |
areas, such as section-wide navigation. |
| 410 |
|
| 411 |
Here are some tips for working with inheritance: |
| 412 |
|
| 413 |
* If you use :ttag:`{% extends %}<extends>` in a template, it must be the first template |
| 414 |
tag in that template. Template inheritance won't work, otherwise. |
| 415 |
|
| 416 |
* More :ttag:`{% block %}<block>` tags in your base templates are better. Remember, |
| 417 |
child templates don't have to define all parent blocks, so you can fill |
| 418 |
in reasonable defaults in a number of blocks, then only define the ones |
| 419 |
you need later. It's better to have more hooks than fewer hooks. |
| 420 |
|
| 421 |
* If you find yourself duplicating content in a number of templates, it |
| 422 |
probably means you should move that content to a ``{% block %}`` in a |
| 423 |
parent template. |
| 424 |
|
| 425 |
* If you need to get the content of the block from the parent template, |
| 426 |
the ``{{ block.super }}`` variable will do the trick. This is useful |
| 427 |
if you want to add to the contents of a parent block instead of |
| 428 |
completely overriding it. Data inserted using ``{{ block.super }}`` will |
| 429 |
not be automatically escaped (see the `next section`_), since it was |
| 430 |
already escaped, if necessary, in the parent template. |
| 431 |
|
| 432 |
* By using the same template name as you are inheriting from, |
| 433 |
:ttag:`{% extends %}<extends>` can be used to inherit a template at the same |
| 434 |
time as overriding it. Combined with ``{{ block.super }}``, this can be a |
| 435 |
powerful way to make small customizations. See |
| 436 |
:ref:`extending_an_overridden_template` in the *Overriding templates* How-to |
| 437 |
for a full example. |
| 438 |
|
| 439 |
* Variables created outside of a :ttag:`{% block %}<block>` using the template |
| 440 |
tag ``as`` syntax can't be used inside the block. For example, this template |
| 441 |
doesn't render anything: |
| 442 |
|
| 443 |
.. code-block:: html+django |
| 444 |
|
| 445 |
{% translate "Title" as title %} |
| 446 |
{% block content %}{{ title }}{% endblock %} |
| 447 |
|
| 448 |
* For extra readability, you can optionally give a *name* to your |
| 449 |
``{% endblock %}`` tag. For example: |
| 450 |
|
| 451 |
.. code-block:: html+django |
| 452 |
|
| 453 |
{% block content %} |
| 454 |
... |
| 455 |
{% endblock content %} |
| 456 |
|
| 457 |
In larger templates, this technique helps you see which ``{% block %}`` |
| 458 |
tags are being closed. |
| 459 |
|
| 460 |
* :ttag:`{% block %}<block>` tags are evaluated first. That's why the content |
| 461 |
of a block is always overridden, regardless of the truthiness of surrounding |
| 462 |
tags. For example, this template will *always* override the content of the |
| 463 |
``title`` block: |
| 464 |
|
| 465 |
.. code-block:: html+django |
| 466 |
|
| 467 |
{% if change_title %} |
| 468 |
{% block title %}Hello!{% endblock title %} |
| 469 |
{% endif %} |
| 470 |
|
| 471 |
Finally, note that you can't define multiple :ttag:`block` tags with the same |
| 472 |
name in the same template. This limitation exists because a block tag works in |
| 473 |
"both" directions. That is, a block tag doesn't just provide a hole to fill -- |
| 474 |
it also defines the content that fills the hole in the *parent*. If there were |
| 475 |
two similarly-named :ttag:`block` tags in a template, that template's parent |
| 476 |
wouldn't know which one of the blocks' content to use. |
| 477 |
|
| 478 |
.. _next section: #automatic-html-escaping |
| 479 |
.. _automatic-html-escaping: |
| 480 |
|
| 481 |
Automatic HTML escaping |
| 482 |
======================= |
| 483 |
|
| 484 |
When generating HTML from templates, there's always a risk that a variable will |
| 485 |
include characters that affect the resulting HTML. For example, consider this |
| 486 |
template fragment: |
| 487 |
|
| 488 |
.. code-block:: html+django |
| 489 |
|
| 490 |
Hello, {{ name }} |
| 491 |
|
| 492 |
At first, this seems like a harmless way to display a user's name, but consider |
| 493 |
what would happen if the user entered their name as this: |
| 494 |
|
| 495 |
.. code-block:: html+django |
| 496 |
|
| 497 |
<script>alert('hello')</script> |
| 498 |
|
| 499 |
With this name value, the template would be rendered as: |
| 500 |
|
| 501 |
.. code-block:: html+django |
| 502 |
|
| 503 |
Hello, <script>alert('hello')</script> |
| 504 |
|
| 505 |
...which means the browser would pop-up a JavaScript alert box! |
| 506 |
|
| 507 |
Similarly, what if the name contained a ``'<'`` symbol, like this? |
| 508 |
|
| 509 |
.. code-block:: html |
| 510 |
|
| 511 |
<b>username |
| 512 |
|
| 513 |
That would result in a rendered template like this: |
| 514 |
|
| 515 |
.. code-block:: html+django |
| 516 |
|
| 517 |
Hello, <b>username |
| 518 |
|
| 519 |
...which, in turn, would result in the remainder of the web page being in bold! |
| 520 |
|
| 521 |
Clearly, user-submitted data shouldn't be trusted blindly and inserted directly |
| 522 |
into your web pages, because a malicious user could use this kind of hole to |
| 523 |
do potentially bad things. This type of security exploit is called a |
| 524 |
`Cross Site Scripting`_ (XSS) attack. |
| 525 |
|
| 526 |
To avoid this problem, you have two options: |
| 527 |
|
| 528 |
* One, you can make sure to run each untrusted variable through the |
| 529 |
:tfilter:`escape` filter (documented below), which converts potentially |
| 530 |
harmful HTML characters to unharmful ones. This was the default solution |
| 531 |
in Django for its first few years, but the problem is that it puts the |
| 532 |
onus on *you*, the developer / template author, to ensure you're escaping |
| 533 |
everything. It's easy to forget to escape data. |
| 534 |
|
| 535 |
* Two, you can take advantage of Django's automatic HTML escaping. The |
| 536 |
remainder of this section describes how auto-escaping works. |
| 537 |
|
| 538 |
By default in Django, every template automatically escapes the output |
| 539 |
of every variable tag. Specifically, these five characters are |
| 540 |
escaped: |
| 541 |
|
| 542 |
* ``<`` is converted to ``<`` |
| 543 |
* ``>`` is converted to ``>`` |
| 544 |
* ``'`` (single quote) is converted to ``'`` |
| 545 |
* ``"`` (double quote) is converted to ``"`` |
| 546 |
* ``&`` is converted to ``&`` |
| 547 |
|
| 548 |
Again, we stress that this behavior is on by default. If you're using Django's |
| 549 |
template system, you're protected. |
| 550 |
|
| 551 |
.. _Cross Site Scripting: https://en.wikipedia.org/wiki/Cross-site_scripting |
| 552 |
|
| 553 |
How to turn it off |
| 554 |
------------------ |
| 555 |
|
| 556 |
If you don't want data to be auto-escaped, on a per-site, per-template level or |
| 557 |
per-variable level, you can turn it off in several ways. |
| 558 |
|
| 559 |
Why would you want to turn it off? Because sometimes, template variables |
| 560 |
contain data that you *intend* to be rendered as raw HTML, in which case you |
| 561 |
don't want their contents to be escaped. For example, you might store a blob of |
| 562 |
HTML in your database and want to embed that directly into your template. Or, |
| 563 |
you might be using Django's template system to produce text that is *not* HTML |
| 564 |
-- like an email message, for instance. |
| 565 |
|
| 566 |
For individual variables |
| 567 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
| 568 |
|
| 569 |
To disable auto-escaping for an individual variable, use the :tfilter:`safe` |
| 570 |
filter: |
| 571 |
|
| 572 |
.. code-block:: html+django |
| 573 |
|
| 574 |
This will be escaped: {{ data }} |
| 575 |
This will not be escaped: {{ data|safe }} |
| 576 |
|
| 577 |
Think of *safe* as shorthand for *safe from further escaping* or *can be |
| 578 |
safely interpreted as HTML*. In this example, if ``data`` contains ``'<b>'``, |
| 579 |
the output will be: |
| 580 |
|
| 581 |
.. code-block:: html+django |
| 582 |
|
| 583 |
This will be escaped: <b> |
| 584 |
This will not be escaped: <b> |
| 585 |
|
| 586 |
For template blocks |
| 587 |
~~~~~~~~~~~~~~~~~~~ |
| 588 |
|
| 589 |
To control auto-escaping for a template, wrap the template (or a particular |
| 590 |
section of the template) in the :ttag:`autoescape` tag, like so: |
| 591 |
|
| 592 |
.. code-block:: html+django |
| 593 |
|
| 594 |
{% autoescape off %} |
| 595 |
Hello {{ name }} |
| 596 |
{% endautoescape %} |
| 597 |
|
| 598 |
The :ttag:`autoescape` tag takes either ``on`` or ``off`` as its argument. At |
| 599 |
times, you might want to force auto-escaping when it would otherwise be |
| 600 |
disabled. Here is an example template: |
| 601 |
|
| 602 |
.. code-block:: html+django |
| 603 |
|
| 604 |
Auto-escaping is on by default. Hello {{ name }} |
| 605 |
|
| 606 |
{% autoescape off %} |
| 607 |
This will not be auto-escaped: {{ data }}. |
| 608 |
|
| 609 |
Nor this: {{ other_data }} |
| 610 |
{% autoescape on %} |
| 611 |
Auto-escaping applies again: {{ name }} |
| 612 |
{% endautoescape %} |
| 613 |
{% endautoescape %} |
| 614 |
|
| 615 |
The auto-escaping tag passes its effect onto templates that extend the |
| 616 |
current one as well as templates included via the :ttag:`include` tag, |
| 617 |
just like all block tags. For example: |
| 618 |
|
| 619 |
.. code-block:: html+django |
| 620 |
:caption: ``base.html`` |
| 621 |
|
| 622 |
{% autoescape off %} |
| 623 |
<h1>{% block title %}{% endblock %}</h1> |
| 624 |
{% block content %} |
| 625 |
{% endblock %} |
| 626 |
{% endautoescape %} |
| 627 |
|
| 628 |
.. code-block:: html+django |
| 629 |
:caption: ``child.html`` |
| 630 |
|
| 631 |
{% extends "base.html" %} |
| 632 |
{% block title %}This & that{% endblock %} |
| 633 |
{% block content %}{{ greeting }}{% endblock %} |
| 634 |
|
| 635 |
Because auto-escaping is turned off in the base template, it will also be |
| 636 |
turned off in the child template, resulting in the following rendered |
| 637 |
HTML when the ``greeting`` variable contains the string ``<b>Hello!</b>``: |
| 638 |
|
| 639 |
.. code-block:: html+django |
| 640 |
|
| 641 |
<h1>This & that</h1> |
| 642 |
<b>Hello!</b> |
| 643 |
|
| 644 |
Notes |
| 645 |
----- |
| 646 |
|
| 647 |
Generally, template authors don't need to worry about auto-escaping very much. |
| 648 |
Developers on the Python side (people writing views and custom filters) need to |
| 649 |
think about the cases in which data shouldn't be escaped, and mark data |
| 650 |
appropriately, so things Just Work in the template. |
| 651 |
|
| 652 |
If you're creating a template that might be used in situations where you're |
| 653 |
not sure whether auto-escaping is enabled, then add an :tfilter:`escape` filter |
| 654 |
to any variable that needs escaping. When auto-escaping is on, there's no |
| 655 |
danger of the :tfilter:`escape` filter *double-escaping* data -- the |
| 656 |
:tfilter:`escape` filter does not affect auto-escaped variables. |
| 657 |
|
| 658 |
.. _string-literals-and-automatic-escaping: |
| 659 |
|
| 660 |
String literals and automatic escaping |
| 661 |
-------------------------------------- |
| 662 |
|
| 663 |
As we mentioned earlier, filter arguments can be strings: |
| 664 |
|
| 665 |
.. code-block:: html+django |
| 666 |
|
| 667 |
{{ data|default:"This is a string literal." }} |
| 668 |
|
| 669 |
All string literals are inserted **without** any automatic escaping into the |
| 670 |
template -- they act as if they were all passed through the :tfilter:`safe` |
| 671 |
filter. The reasoning behind this is that the template author is in control of |
| 672 |
what goes into the string literal, so they can make sure the text is correctly |
| 673 |
escaped when the template is written. |
| 674 |
|
| 675 |
This means you would write : |
| 676 |
|
| 677 |
.. code-block:: html+django |
| 678 |
|
| 679 |
{{ data|default:"3 < 2" }} |
| 680 |
|
| 681 |
...rather than: |
| 682 |
|
| 683 |
.. code-block:: html+django |
| 684 |
|
| 685 |
{{ data|default:"3 < 2" }} {# Bad! Don't do this. #} |
| 686 |
|
| 687 |
This doesn't affect what happens to data coming from the variable itself. |
| 688 |
The variable's contents are still automatically escaped, if necessary, because |
| 689 |
they're beyond the control of the template author. |
| 690 |
|
| 691 |
.. _template-accessing-methods: |
| 692 |
|
| 693 |
Accessing method calls |
| 694 |
====================== |
| 695 |
|
| 696 |
Most method calls attached to objects are also available from within templates. |
| 697 |
This means that templates have access to much more than just class attributes |
| 698 |
(like field names) and variables passed in from views. For example, the Django |
| 699 |
ORM provides the :ref:`"entry_set"<topics-db-queries-related>` syntax for |
| 700 |
finding a collection of objects related on a foreign key. Therefore, given |
| 701 |
a model called "comment" with a foreign key relationship to a model called |
| 702 |
"task" you can loop through all comments attached to a given task like this: |
| 703 |
|
| 704 |
.. code-block:: html+django |
| 705 |
|
| 706 |
{% for comment in task.comment_set.all %} |
| 707 |
{{ comment }} |
| 708 |
{% endfor %} |
| 709 |
|
| 710 |
Similarly, :doc:`QuerySets</ref/models/querysets>` provide a ``count()`` method |
| 711 |
to count the number of objects they contain. Therefore, you can obtain a count |
| 712 |
of all comments related to the current task with: |
| 713 |
|
| 714 |
.. code-block:: html+django |
| 715 |
|
| 716 |
{{ task.comment_set.all.count }} |
| 717 |
|
| 718 |
You can also access methods you've explicitly defined on your own models: |
| 719 |
|
| 720 |
.. code-block:: python |
| 721 |
:caption: ``models.py`` |
| 722 |
|
| 723 |
class Task(models.Model): |
| 724 |
def foo(self): |
| 725 |
return "bar" |
| 726 |
|
| 727 |
.. code-block:: html+django |
| 728 |
:caption: ``template.html`` |
| 729 |
|
| 730 |
{{ task.foo }} |
| 731 |
|
| 732 |
Because Django intentionally limits the amount of logic processing available |
| 733 |
in the template language, it is not possible to pass arguments to method calls |
| 734 |
accessed from within templates. Data should be calculated in views, then passed |
| 735 |
to templates for display. |
| 736 |
|
| 737 |
.. _loading-custom-template-libraries: |
| 738 |
|
| 739 |
Custom tag and filter libraries |
| 740 |
=============================== |
| 741 |
|
| 742 |
Certain applications provide custom tag and filter libraries. To access them in |
| 743 |
a template, ensure the application is in :setting:`INSTALLED_APPS` (we'd add |
| 744 |
``'django.contrib.humanize'`` for this example), and then use the :ttag:`load` |
| 745 |
tag in a template: |
| 746 |
|
| 747 |
.. code-block:: html+django |
| 748 |
|
| 749 |
{% load humanize %} |
| 750 |
|
| 751 |
{{ 45000|intcomma }} |
| 752 |
|
| 753 |
In the above, the :ttag:`load` tag loads the ``humanize`` tag library, which then |
| 754 |
makes the ``intcomma`` filter available for use. If you've enabled |
| 755 |
:mod:`django.contrib.admindocs`, you can consult the documentation area in your |
| 756 |
admin to find the list of custom libraries in your installation. |
| 757 |
|
| 758 |
The :ttag:`load` tag can take multiple library names, separated by spaces. |
| 759 |
Example: |
| 760 |
|
| 761 |
.. code-block:: html+django |
| 762 |
|
| 763 |
{% load humanize i18n %} |
| 764 |
|
| 765 |
See :doc:`/howto/custom-template-tags` for information on writing your own custom |
| 766 |
template libraries. |
| 767 |
|
| 768 |
Custom libraries and template inheritance |
| 769 |
----------------------------------------- |
| 770 |
|
| 771 |
When you load a custom tag or filter library, the tags/filters are only made |
| 772 |
available to the current template -- not any parent or child templates along |
| 773 |
the template-inheritance path. |
| 774 |
|
| 775 |
For example, if a template ``foo.html`` has ``{% load humanize %}``, a child |
| 776 |
template (e.g., one that has ``{% extends "foo.html" %}``) will *not* have |
| 777 |
access to the humanize template tags and filters. The child template is |
| 778 |
responsible for its own ``{% load humanize %}``. |
| 779 |
|
| 780 |
This is a feature for the sake of maintainability and sanity. |
| 781 |
|
| 782 |
.. seealso:: |
| 783 |
|
| 784 |
:doc:`The Templates Reference </ref/templates/index>` |
| 785 |
Covers built-in tags, built-in filters, using an alternative template |
| 786 |
language, and more. |