| 1 |
================================== |
| 2 |
Built-in template tags and filters |
| 3 |
================================== |
| 4 |
|
| 5 |
This document describes Django's built-in template tags and filters. It is |
| 6 |
recommended that you use the :doc:`automatic documentation |
| 7 |
</ref/contrib/admin/admindocs>`, if available, as this will also include |
| 8 |
documentation for any custom tags or filters installed. |
| 9 |
|
| 10 |
.. _ref-templates-builtins-tags: |
| 11 |
|
| 12 |
Built-in tag reference |
| 13 |
====================== |
| 14 |
|
| 15 |
.. templatetag:: autoescape |
| 16 |
|
| 17 |
``autoescape`` |
| 18 |
-------------- |
| 19 |
|
| 20 |
Controls the current auto-escaping behavior. This tag takes either ``on`` or |
| 21 |
``off`` as an argument and that determines whether auto-escaping is in effect |
| 22 |
inside the block. The block is closed with an ``endautoescape`` ending tag. |
| 23 |
|
| 24 |
Sample usage: |
| 25 |
|
| 26 |
.. code-block:: html+django |
| 27 |
|
| 28 |
{% autoescape on %} |
| 29 |
{{ body }} |
| 30 |
{% endautoescape %} |
| 31 |
|
| 32 |
When auto-escaping is in effect, all content derived from variables has HTML |
| 33 |
escaping applied before placing the result into the output (but after any |
| 34 |
filters are applied). This is equivalent to manually applying the |
| 35 |
:tfilter:`escape` filter to each variable. |
| 36 |
|
| 37 |
The only exceptions are variables already marked as "safe" from escaping. |
| 38 |
Variables could be marked as "safe" by the code which populated the variable, |
| 39 |
by applying the :tfilter:`safe` or :tfilter:`escape` filters, or because it's |
| 40 |
the result of a previous filter that marked the string as "safe". |
| 41 |
|
| 42 |
Within the scope of disabled auto-escaping, chaining filters, including |
| 43 |
:tfilter:`escape`, may cause unexpected (but documented) results such as the |
| 44 |
following: |
| 45 |
|
| 46 |
.. code-block:: html+django |
| 47 |
|
| 48 |
{% autoescape off %} |
| 49 |
{{ my_list|join:", "|escape }} |
| 50 |
{% endautoescape %} |
| 51 |
|
| 52 |
The above code will output the joined elements of ``my_list`` unescaped. This |
| 53 |
is because the filter chaining sequence executes first :tfilter:`join` on |
| 54 |
``my_list`` (without applying escaping to each item since ``autoescape`` is |
| 55 |
``off``), marking the result as safe. Subsequently, this safe result will be |
| 56 |
fed to :tfilter:`escape` filter, which does not apply a second round of |
| 57 |
escaping. |
| 58 |
|
| 59 |
In order to properly escape every element in a sequence, use the |
| 60 |
:tfilter:`escapeseq` filter: |
| 61 |
|
| 62 |
.. code-block:: html+django |
| 63 |
|
| 64 |
{% autoescape off %} |
| 65 |
{{ my_list|escapeseq|join:", " }} |
| 66 |
{% endautoescape %} |
| 67 |
|
| 68 |
.. templatetag:: block |
| 69 |
|
| 70 |
``block`` |
| 71 |
--------- |
| 72 |
|
| 73 |
Defines a block that can be overridden by child templates. See |
| 74 |
:ref:`Template inheritance <template-inheritance>` for more information. |
| 75 |
|
| 76 |
.. templatetag:: comment |
| 77 |
|
| 78 |
``comment`` |
| 79 |
----------- |
| 80 |
|
| 81 |
Ignores everything between ``{% comment %}`` and ``{% endcomment %}``. |
| 82 |
An optional note may be inserted in the first tag. For example, this is |
| 83 |
useful when commenting out code for documenting why the code was disabled. |
| 84 |
|
| 85 |
Sample usage: |
| 86 |
|
| 87 |
.. code-block:: html+django |
| 88 |
|
| 89 |
<p>Rendered text with {{ pub_date|date:"c" }}</p> |
| 90 |
{% comment "Optional note" %} |
| 91 |
<p>Commented out text with {{ create_date|date:"c" }}</p> |
| 92 |
{% endcomment %} |
| 93 |
|
| 94 |
``comment`` tags cannot be nested. |
| 95 |
|
| 96 |
.. templatetag:: csrf_token |
| 97 |
|
| 98 |
``csrf_token`` |
| 99 |
-------------- |
| 100 |
|
| 101 |
This tag is used for CSRF protection, as described in the documentation for |
| 102 |
:doc:`Cross Site Request Forgeries </ref/csrf>`. |
| 103 |
|
| 104 |
.. templatetag:: cycle |
| 105 |
|
| 106 |
``cycle`` |
| 107 |
--------- |
| 108 |
|
| 109 |
Produces one of its arguments each time this tag is encountered. The first |
| 110 |
argument is produced on the first encounter, the second argument on the second |
| 111 |
encounter, and so forth. Once all arguments are exhausted, the tag cycles to |
| 112 |
the first argument and produces it again. |
| 113 |
|
| 114 |
This tag is particularly useful in a loop: |
| 115 |
|
| 116 |
.. code-block:: html+django |
| 117 |
|
| 118 |
{% for o in some_list %} |
| 119 |
<tr class="{% cycle 'row1' 'row2' %}"> |
| 120 |
... |
| 121 |
</tr> |
| 122 |
{% endfor %} |
| 123 |
|
| 124 |
The first iteration produces HTML that refers to class ``row1``, the second to |
| 125 |
``row2``, the third to ``row1`` again, and so on for each iteration of the |
| 126 |
loop. |
| 127 |
|
| 128 |
You can use variables, too. For example, if you have two template variables, |
| 129 |
``rowvalue1`` and ``rowvalue2``, you can alternate between their values like |
| 130 |
this: |
| 131 |
|
| 132 |
.. code-block:: html+django |
| 133 |
|
| 134 |
{% for o in some_list %} |
| 135 |
<tr class="{% cycle rowvalue1 rowvalue2 %}"> |
| 136 |
... |
| 137 |
</tr> |
| 138 |
{% endfor %} |
| 139 |
|
| 140 |
Variables included in the cycle will be escaped. You can disable auto-escaping |
| 141 |
with: |
| 142 |
|
| 143 |
.. code-block:: html+django |
| 144 |
|
| 145 |
{% for o in some_list %} |
| 146 |
<tr class="{% autoescape off %}{% cycle rowvalue1 rowvalue2 %}{% endautoescape %}"> |
| 147 |
... |
| 148 |
</tr> |
| 149 |
{% endfor %} |
| 150 |
|
| 151 |
You can mix variables and strings: |
| 152 |
|
| 153 |
.. code-block:: html+django |
| 154 |
|
| 155 |
{% for o in some_list %} |
| 156 |
<tr class="{% cycle 'row1' rowvalue2 'row3' %}"> |
| 157 |
... |
| 158 |
</tr> |
| 159 |
{% endfor %} |
| 160 |
|
| 161 |
In some cases you might want to refer to the current value of a cycle |
| 162 |
without advancing to the next value. To do this, |
| 163 |
give the ``{% cycle %}`` tag a name, using "as", like this: |
| 164 |
|
| 165 |
.. code-block:: html+django |
| 166 |
|
| 167 |
{% cycle 'row1' 'row2' as rowcolors %} |
| 168 |
|
| 169 |
From then on, you can insert the current value of the cycle wherever you'd like |
| 170 |
in your template by referencing the cycle name as a context variable. If you |
| 171 |
want to move the cycle to the next value independently of the original |
| 172 |
``cycle`` tag, you can use another ``cycle`` tag and specify the name of the |
| 173 |
variable. So, the following template: |
| 174 |
|
| 175 |
.. code-block:: html+django |
| 176 |
|
| 177 |
<tr> |
| 178 |
<td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td> |
| 179 |
<td class="{{ rowcolors }}">...</td> |
| 180 |
</tr> |
| 181 |
<tr> |
| 182 |
<td class="{% cycle rowcolors %}">...</td> |
| 183 |
<td class="{{ rowcolors }}">...</td> |
| 184 |
</tr> |
| 185 |
|
| 186 |
would output: |
| 187 |
|
| 188 |
.. code-block:: html+django |
| 189 |
|
| 190 |
<tr> |
| 191 |
<td class="row1">...</td> |
| 192 |
<td class="row1">...</td> |
| 193 |
</tr> |
| 194 |
<tr> |
| 195 |
<td class="row2">...</td> |
| 196 |
<td class="row2">...</td> |
| 197 |
</tr> |
| 198 |
|
| 199 |
You can use any number of values in a ``cycle`` tag, separated by spaces. |
| 200 |
Values enclosed in single quotes (``'``) or double quotes (``"``) are treated |
| 201 |
as string literals, while values without quotes are treated as template |
| 202 |
variables. |
| 203 |
|
| 204 |
By default, when you use the ``as`` keyword with the cycle tag, the |
| 205 |
usage of ``{% cycle %}`` that initiates the cycle will itself produce |
| 206 |
the first value in the cycle. This could be a problem if you want to |
| 207 |
use the value in a nested loop or an included template. If you only want |
| 208 |
to declare the cycle but not produce the first value, you can add a |
| 209 |
``silent`` keyword as the last keyword in the tag. For example: |
| 210 |
|
| 211 |
.. code-block:: html+django |
| 212 |
|
| 213 |
{% for obj in some_list %} |
| 214 |
{% cycle 'row1' 'row2' as rowcolors silent %} |
| 215 |
<tr class="{{ rowcolors }}">{% include "subtemplate.html" %}</tr> |
| 216 |
{% endfor %} |
| 217 |
|
| 218 |
This will output a list of ``<tr>`` elements with ``class`` |
| 219 |
alternating between ``row1`` and ``row2``. The subtemplate will have |
| 220 |
access to ``rowcolors`` in its context and the value will match the class |
| 221 |
of the ``<tr>`` that encloses it. If the ``silent`` keyword were to be |
| 222 |
omitted, ``row1`` and ``row2`` would be emitted as normal text, outside the |
| 223 |
``<tr>`` element. |
| 224 |
|
| 225 |
When the silent keyword is used on a cycle definition, the silence |
| 226 |
automatically applies to all subsequent uses of that specific cycle tag. |
| 227 |
The following template would output *nothing*, even though the second |
| 228 |
call to ``{% cycle %}`` doesn't specify ``silent``: |
| 229 |
|
| 230 |
.. code-block:: html+django |
| 231 |
|
| 232 |
{% cycle 'row1' 'row2' as rowcolors silent %} |
| 233 |
{% cycle rowcolors %} |
| 234 |
|
| 235 |
You can use the :ttag:`resetcycle` tag to make a ``{% cycle %}`` tag restart |
| 236 |
from its first value when it's next encountered. |
| 237 |
|
| 238 |
.. templatetag:: debug |
| 239 |
|
| 240 |
``debug`` |
| 241 |
--------- |
| 242 |
|
| 243 |
Outputs a whole load of debugging information, including the current context |
| 244 |
and imported modules. ``{% debug %}`` outputs nothing when the :setting:`DEBUG` |
| 245 |
setting is ``False``. |
| 246 |
|
| 247 |
.. templatetag:: extends |
| 248 |
|
| 249 |
``extends`` |
| 250 |
----------- |
| 251 |
|
| 252 |
Signals that this template extends a parent template. |
| 253 |
|
| 254 |
This tag can be used in two ways: |
| 255 |
|
| 256 |
* ``{% extends "base.html" %}`` (with quotes) uses the literal value |
| 257 |
``"base.html"`` as the name of the parent template to extend. |
| 258 |
|
| 259 |
* ``{% extends variable %}`` uses the value of ``variable``. If the variable |
| 260 |
evaluates to a string, Django will use that string as the name of the |
| 261 |
parent template. If the variable evaluates to a ``Template`` object, |
| 262 |
Django will use that object as the parent template. |
| 263 |
|
| 264 |
See :ref:`template-inheritance` for more information. |
| 265 |
|
| 266 |
Normally the template name is relative to the template loader's root directory. |
| 267 |
A string argument may also be a relative path starting with ``./`` or ``../``. |
| 268 |
For example, assume the following directory structure: |
| 269 |
|
| 270 |
.. code-block:: text |
| 271 |
|
| 272 |
dir1/ |
| 273 |
template.html |
| 274 |
base2.html |
| 275 |
my/ |
| 276 |
base3.html |
| 277 |
base1.html |
| 278 |
|
| 279 |
In ``template.html``, the following paths would be valid: |
| 280 |
|
| 281 |
.. code-block:: html+django |
| 282 |
|
| 283 |
{% extends "./base2.html" %} |
| 284 |
{% extends "../base1.html" %} |
| 285 |
{% extends "./my/base3.html" %} |
| 286 |
|
| 287 |
.. templatetag:: filter |
| 288 |
|
| 289 |
``filter`` |
| 290 |
---------- |
| 291 |
|
| 292 |
Filters the contents of the block through one or more filters. Multiple |
| 293 |
filters can be specified with pipes and filters can have arguments, just as |
| 294 |
in variable syntax. |
| 295 |
|
| 296 |
Note that the block includes *all* the text between the ``filter`` and |
| 297 |
``endfilter`` tags. |
| 298 |
|
| 299 |
Sample usage: |
| 300 |
|
| 301 |
.. code-block:: html+django |
| 302 |
|
| 303 |
{% filter force_escape|lower %} |
| 304 |
This text will be HTML-escaped, and will appear in all lowercase. |
| 305 |
{% endfilter %} |
| 306 |
|
| 307 |
.. note:: |
| 308 |
|
| 309 |
The :tfilter:`escape` and :tfilter:`safe` filters are not acceptable |
| 310 |
arguments. Instead, use the :ttag:`autoescape` tag to manage autoescaping |
| 311 |
for blocks of template code. |
| 312 |
|
| 313 |
.. templatetag:: firstof |
| 314 |
|
| 315 |
``firstof`` |
| 316 |
----------- |
| 317 |
|
| 318 |
Outputs the first argument variable that is not "false" (i.e. exists, is not |
| 319 |
empty, is not a false boolean value, and is not a zero numeric value). Outputs |
| 320 |
nothing if all the passed variables are "false". |
| 321 |
|
| 322 |
Sample usage: |
| 323 |
|
| 324 |
.. code-block:: html+django |
| 325 |
|
| 326 |
{% firstof var1 var2 var3 %} |
| 327 |
|
| 328 |
This is equivalent to: |
| 329 |
|
| 330 |
.. code-block:: html+django |
| 331 |
|
| 332 |
{% if var1 %} |
| 333 |
{{ var1 }} |
| 334 |
{% elif var2 %} |
| 335 |
{{ var2 }} |
| 336 |
{% elif var3 %} |
| 337 |
{{ var3 }} |
| 338 |
{% endif %} |
| 339 |
|
| 340 |
You can also use a literal string as a fallback value in case all |
| 341 |
passed variables are False: |
| 342 |
|
| 343 |
.. code-block:: html+django |
| 344 |
|
| 345 |
{% firstof var1 var2 var3 "fallback value" %} |
| 346 |
|
| 347 |
This tag auto-escapes variable values. You can disable auto-escaping with: |
| 348 |
|
| 349 |
.. code-block:: html+django |
| 350 |
|
| 351 |
{% autoescape off %} |
| 352 |
{% firstof var1 var2 var3 "<strong>fallback value</strong>" %} |
| 353 |
{% endautoescape %} |
| 354 |
|
| 355 |
Or if only some variables should be escaped, you can use: |
| 356 |
|
| 357 |
.. code-block:: html+django |
| 358 |
|
| 359 |
{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %} |
| 360 |
|
| 361 |
You can use the syntax ``{% firstof var1 var2 var3 as value %}`` to store the |
| 362 |
output inside a variable. |
| 363 |
|
| 364 |
.. templatetag:: for |
| 365 |
|
| 366 |
``for`` |
| 367 |
------- |
| 368 |
|
| 369 |
Loops over each item in an array, making the item available in a context |
| 370 |
variable. For example, to display a list of athletes provided in |
| 371 |
``athlete_list``: |
| 372 |
|
| 373 |
.. code-block:: html+django |
| 374 |
|
| 375 |
<ul> |
| 376 |
{% for athlete in athlete_list %} |
| 377 |
<li>{{ athlete.name }}</li> |
| 378 |
{% endfor %} |
| 379 |
</ul> |
| 380 |
|
| 381 |
You can loop over a list in reverse by using |
| 382 |
``{% for obj in list reversed %}``. |
| 383 |
|
| 384 |
If you need to loop over a list of lists, you can unpack the values |
| 385 |
in each sublist into individual variables. For example, if your context |
| 386 |
contains a list of (x,y) coordinates called ``points``, you could use the |
| 387 |
following to output the list of points: |
| 388 |
|
| 389 |
.. code-block:: html+django |
| 390 |
|
| 391 |
{% for x, y in points %} |
| 392 |
There is a point at {{ x }},{{ y }} |
| 393 |
{% endfor %} |
| 394 |
|
| 395 |
This can also be useful if you need to access the items in a dictionary. |
| 396 |
For example, if your context contained a dictionary ``data``, the following |
| 397 |
would display the keys and values of the dictionary: |
| 398 |
|
| 399 |
.. code-block:: html+django |
| 400 |
|
| 401 |
{% for key, value in data.items %} |
| 402 |
{{ key }}: {{ value }} |
| 403 |
{% endfor %} |
| 404 |
|
| 405 |
Keep in mind that for the dot operator, dictionary key lookup takes precedence |
| 406 |
over method lookup. Therefore if the ``data`` dictionary contains a key named |
| 407 |
``'items'``, ``data.items`` will return ``data['items']`` instead of |
| 408 |
``data.items()``. Avoid adding keys that are named like dictionary methods if |
| 409 |
you want to use those methods in a template (``items``, ``values``, ``keys``, |
| 410 |
etc.). Read more about the lookup order of the dot operator in the |
| 411 |
:ref:`documentation of template variables <template-variables>`. |
| 412 |
|
| 413 |
The for loop sets a number of variables available within the loop: |
| 414 |
|
| 415 |
========================== =============================================== |
| 416 |
Variable Description |
| 417 |
========================== =============================================== |
| 418 |
``forloop.counter`` The current iteration of the loop (1-indexed) |
| 419 |
``forloop.counter0`` The current iteration of the loop (0-indexed) |
| 420 |
``forloop.revcounter`` The number of iterations from the end of the |
| 421 |
loop (1-indexed) |
| 422 |
``forloop.revcounter0`` The number of iterations from the end of the |
| 423 |
loop (0-indexed) |
| 424 |
``forloop.first`` True if this is the first time through the loop |
| 425 |
``forloop.last`` True if this is the last time through the loop |
| 426 |
``forloop.parentloop`` For nested loops, this is the loop surrounding |
| 427 |
the current one |
| 428 |
========================== =============================================== |
| 429 |
|
| 430 |
``for`` ... ``empty`` |
| 431 |
--------------------- |
| 432 |
|
| 433 |
The ``for`` tag can take an optional ``{% empty %}`` clause whose text is |
| 434 |
displayed if the given array is empty or could not be found: |
| 435 |
|
| 436 |
.. code-block:: html+django |
| 437 |
|
| 438 |
<ul> |
| 439 |
{% for athlete in athlete_list %} |
| 440 |
<li>{{ athlete.name }}</li> |
| 441 |
{% empty %} |
| 442 |
<li>Sorry, no athletes in this list.</li> |
| 443 |
{% endfor %} |
| 444 |
</ul> |
| 445 |
|
| 446 |
The above is equivalent to -- but shorter, cleaner, and possibly faster |
| 447 |
than -- the following: |
| 448 |
|
| 449 |
.. code-block:: html+django |
| 450 |
|
| 451 |
<ul> |
| 452 |
{% if athlete_list %} |
| 453 |
{% for athlete in athlete_list %} |
| 454 |
<li>{{ athlete.name }}</li> |
| 455 |
{% endfor %} |
| 456 |
{% else %} |
| 457 |
<li>Sorry, no athletes in this list.</li> |
| 458 |
{% endif %} |
| 459 |
</ul> |
| 460 |
|
| 461 |
.. templatetag:: if |
| 462 |
|
| 463 |
``if`` |
| 464 |
------ |
| 465 |
|
| 466 |
The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e. |
| 467 |
exists, is not empty, and is not a false boolean value) the contents of the |
| 468 |
block are output: |
| 469 |
|
| 470 |
.. code-block:: html+django |
| 471 |
|
| 472 |
{% if athlete_list %} |
| 473 |
Number of athletes: {{ athlete_list|length }} |
| 474 |
{% elif athlete_in_locker_room_list %} |
| 475 |
Athletes should be out of the locker room soon! |
| 476 |
{% else %} |
| 477 |
No athletes. |
| 478 |
{% endif %} |
| 479 |
|
| 480 |
In the above, if ``athlete_list`` is not empty, the number of athletes will be |
| 481 |
displayed by the ``{{ athlete_list|length }}`` variable. |
| 482 |
|
| 483 |
As you can see, the ``if`` tag may take one or several ``{% elif %}`` |
| 484 |
clauses, as well as an ``{% else %}`` clause that will be displayed if all |
| 485 |
previous conditions fail. These clauses are optional. |
| 486 |
|
| 487 |
Boolean operators |
| 488 |
~~~~~~~~~~~~~~~~~ |
| 489 |
|
| 490 |
:ttag:`if` tags may use ``and``, ``or`` or ``not`` to test a number of |
| 491 |
variables or to negate a given variable: |
| 492 |
|
| 493 |
.. code-block:: html+django |
| 494 |
|
| 495 |
{% if athlete_list and coach_list %} |
| 496 |
Both athletes and coaches are available. |
| 497 |
{% endif %} |
| 498 |
|
| 499 |
{% if not athlete_list %} |
| 500 |
There are no athletes. |
| 501 |
{% endif %} |
| 502 |
|
| 503 |
{% if athlete_list or coach_list %} |
| 504 |
There are some athletes or some coaches. |
| 505 |
{% endif %} |
| 506 |
|
| 507 |
{% if not athlete_list or coach_list %} |
| 508 |
There are no athletes or there are some coaches. |
| 509 |
{% endif %} |
| 510 |
|
| 511 |
{% if athlete_list and not coach_list %} |
| 512 |
There are some athletes and absolutely no coaches. |
| 513 |
{% endif %} |
| 514 |
|
| 515 |
Use of both ``and`` and ``or`` clauses within the same tag is allowed, with |
| 516 |
``and`` having higher precedence than ``or`` e.g.: |
| 517 |
|
| 518 |
.. code-block:: html+django |
| 519 |
|
| 520 |
{% if athlete_list and coach_list or cheerleader_list %} |
| 521 |
|
| 522 |
will be interpreted like:: |
| 523 |
|
| 524 |
if (athlete_list and coach_list) or cheerleader_list: |
| 525 |
... |
| 526 |
|
| 527 |
Use of actual parentheses in the :ttag:`if` tag is invalid syntax. If you need |
| 528 |
them to indicate precedence, you should use nested :ttag:`if` tags. |
| 529 |
|
| 530 |
:ttag:`if` tags may also use the operators ``==``, ``!=``, ``<``, ``>``, |
| 531 |
``<=``, ``>=``, ``in``, ``not in``, ``is``, and ``is not`` which work as |
| 532 |
follows: |
| 533 |
|
| 534 |
``==`` operator |
| 535 |
^^^^^^^^^^^^^^^ |
| 536 |
|
| 537 |
Equality. Example: |
| 538 |
|
| 539 |
.. code-block:: html+django |
| 540 |
|
| 541 |
{% if somevar == "x" %} |
| 542 |
This appears if variable somevar equals the string "x" |
| 543 |
{% endif %} |
| 544 |
|
| 545 |
``!=`` operator |
| 546 |
^^^^^^^^^^^^^^^ |
| 547 |
|
| 548 |
Inequality. Example: |
| 549 |
|
| 550 |
.. code-block:: html+django |
| 551 |
|
| 552 |
{% if somevar != "x" %} |
| 553 |
This appears if variable somevar does not equal the string "x", |
| 554 |
or if somevar is not found in the context |
| 555 |
{% endif %} |
| 556 |
|
| 557 |
``<`` operator |
| 558 |
^^^^^^^^^^^^^^ |
| 559 |
|
| 560 |
Less than. Example: |
| 561 |
|
| 562 |
.. code-block:: html+django |
| 563 |
|
| 564 |
{% if somevar < 100 %} |
| 565 |
This appears if variable somevar is less than 100. |
| 566 |
{% endif %} |
| 567 |
|
| 568 |
``>`` operator |
| 569 |
^^^^^^^^^^^^^^ |
| 570 |
|
| 571 |
Greater than. Example: |
| 572 |
|
| 573 |
.. code-block:: html+django |
| 574 |
|
| 575 |
{% if somevar > 0 %} |
| 576 |
This appears if variable somevar is greater than 0. |
| 577 |
{% endif %} |
| 578 |
|
| 579 |
``<=`` operator |
| 580 |
^^^^^^^^^^^^^^^ |
| 581 |
|
| 582 |
Less than or equal to. Example: |
| 583 |
|
| 584 |
.. code-block:: html+django |
| 585 |
|
| 586 |
{% if somevar <= 100 %} |
| 587 |
This appears if variable somevar is less than 100 or equal to 100. |
| 588 |
{% endif %} |
| 589 |
|
| 590 |
``>=`` operator |
| 591 |
^^^^^^^^^^^^^^^ |
| 592 |
|
| 593 |
Greater than or equal to. Example: |
| 594 |
|
| 595 |
.. code-block:: html+django |
| 596 |
|
| 597 |
{% if somevar >= 1 %} |
| 598 |
This appears if variable somevar is greater than 1 or equal to 1. |
| 599 |
{% endif %} |
| 600 |
|
| 601 |
``in`` operator |
| 602 |
^^^^^^^^^^^^^^^ |
| 603 |
|
| 604 |
Contained within. This operator is supported by many Python containers to test |
| 605 |
whether the given value is in the container. The following are some examples |
| 606 |
of how ``x in y`` will be interpreted: |
| 607 |
|
| 608 |
.. code-block:: html+django |
| 609 |
|
| 610 |
{% if "bc" in "abcdef" %} |
| 611 |
This appears since "bc" is a substring of "abcdef" |
| 612 |
{% endif %} |
| 613 |
|
| 614 |
{% if "hello" in greetings %} |
| 615 |
If greetings is a list or set, one element of which is the string |
| 616 |
"hello", this will appear. |
| 617 |
{% endif %} |
| 618 |
|
| 619 |
{% if user in users %} |
| 620 |
If users is a QuerySet, this will appear if user is an |
| 621 |
instance that belongs to the QuerySet. |
| 622 |
{% endif %} |
| 623 |
|
| 624 |
``not in`` operator |
| 625 |
^^^^^^^^^^^^^^^^^^^ |
| 626 |
|
| 627 |
Not contained within. This is the negation of the ``in`` operator. |
| 628 |
|
| 629 |
``is`` operator |
| 630 |
^^^^^^^^^^^^^^^ |
| 631 |
|
| 632 |
Object identity. Tests if two values are the same object. Example: |
| 633 |
|
| 634 |
.. code-block:: html+django |
| 635 |
|
| 636 |
{% if somevar is True %} |
| 637 |
This appears if and only if somevar is True. |
| 638 |
{% endif %} |
| 639 |
|
| 640 |
{% if somevar is None %} |
| 641 |
This appears if somevar is None, or if somevar is not found in the context. |
| 642 |
{% endif %} |
| 643 |
|
| 644 |
``is not`` operator |
| 645 |
^^^^^^^^^^^^^^^^^^^ |
| 646 |
|
| 647 |
Negated object identity. Tests if two values are not the same object. This is |
| 648 |
the negation of the ``is`` operator. Example: |
| 649 |
|
| 650 |
.. code-block:: html+django |
| 651 |
|
| 652 |
{% if somevar is not True %} |
| 653 |
This appears if somevar is not True, or if somevar is not found in the |
| 654 |
context. |
| 655 |
{% endif %} |
| 656 |
|
| 657 |
{% if somevar is not None %} |
| 658 |
This appears if and only if somevar is not None. |
| 659 |
{% endif %} |
| 660 |
|
| 661 |
Filters |
| 662 |
~~~~~~~ |
| 663 |
|
| 664 |
You can also use filters in the :ttag:`if` expression. For example: |
| 665 |
|
| 666 |
.. code-block:: html+django |
| 667 |
|
| 668 |
{% if messages|length >= 100 %} |
| 669 |
You have lots of messages today! |
| 670 |
{% endif %} |
| 671 |
|
| 672 |
Complex expressions |
| 673 |
~~~~~~~~~~~~~~~~~~~ |
| 674 |
|
| 675 |
All of the above can be combined to form complex expressions. For such |
| 676 |
expressions, it can be important to know how the operators are grouped when the |
| 677 |
expression is evaluated - that is, the precedence rules. The precedence of the |
| 678 |
operators, from lowest to highest, is as follows: |
| 679 |
|
| 680 |
* ``or`` |
| 681 |
* ``and`` |
| 682 |
* ``not`` |
| 683 |
* ``in`` |
| 684 |
* ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=`` |
| 685 |
|
| 686 |
(This follows Python exactly). So, for example, the following complex |
| 687 |
:ttag:`if` tag: |
| 688 |
|
| 689 |
.. code-block:: html+django |
| 690 |
|
| 691 |
{% if a == b or c == d and e %} |
| 692 |
|
| 693 |
...will be interpreted as: |
| 694 |
|
| 695 |
.. code-block:: python |
| 696 |
|
| 697 |
(a == b) or ((c == d) and e) |
| 698 |
|
| 699 |
If you need different precedence, you will need to use nested :ttag:`if` tags. |
| 700 |
Sometimes that is better for clarity anyway, for the sake of those who do not |
| 701 |
know the precedence rules. |
| 702 |
|
| 703 |
The comparison operators cannot be 'chained' like in Python or in mathematical |
| 704 |
notation. For example, instead of using: |
| 705 |
|
| 706 |
.. code-block:: html+django |
| 707 |
|
| 708 |
{% if a > b > c %} (WRONG) |
| 709 |
|
| 710 |
you should use: |
| 711 |
|
| 712 |
.. code-block:: html+django |
| 713 |
|
| 714 |
{% if a > b and b > c %} |
| 715 |
|
| 716 |
.. templatetag:: ifchanged |
| 717 |
|
| 718 |
``ifchanged`` |
| 719 |
------------- |
| 720 |
|
| 721 |
Check if a value has changed from the last iteration of a loop. |
| 722 |
|
| 723 |
The ``{% ifchanged %}`` block tag is used within a loop. It has two possible |
| 724 |
uses. |
| 725 |
|
| 726 |
1. Checks its own rendered contents against its previous state and only |
| 727 |
displays the content if it has changed. For example, this displays a list of |
| 728 |
days, only displaying the month if it changes: |
| 729 |
|
| 730 |
.. code-block:: html+django |
| 731 |
|
| 732 |
<h1>Archive for {{ year }}</h1> |
| 733 |
|
| 734 |
{% for date in days %} |
| 735 |
{% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} |
| 736 |
<a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> |
| 737 |
{% endfor %} |
| 738 |
|
| 739 |
2. If given one or more variables, check whether any variable has changed. |
| 740 |
For example, the following shows the date every time it changes, while |
| 741 |
showing the hour if either the hour or the date has changed: |
| 742 |
|
| 743 |
.. code-block:: html+django |
| 744 |
|
| 745 |
{% for date in days %} |
| 746 |
{% ifchanged date.date %} {{ date.date }} {% endifchanged %} |
| 747 |
{% ifchanged date.hour date.date %} |
| 748 |
{{ date.hour }} |
| 749 |
{% endifchanged %} |
| 750 |
{% endfor %} |
| 751 |
|
| 752 |
The ``ifchanged`` tag can also take an optional ``{% else %}`` clause that |
| 753 |
will be displayed if the value has not changed: |
| 754 |
|
| 755 |
.. code-block:: html+django |
| 756 |
|
| 757 |
{% for match in matches %} |
| 758 |
<div style="background-color: |
| 759 |
{% ifchanged match.ballot_id %} |
| 760 |
{% cycle "red" "blue" %} |
| 761 |
{% else %} |
| 762 |
gray |
| 763 |
{% endifchanged %} |
| 764 |
">{{ match }}</div> |
| 765 |
{% endfor %} |
| 766 |
|
| 767 |
.. templatetag:: include |
| 768 |
|
| 769 |
``include`` |
| 770 |
----------- |
| 771 |
|
| 772 |
Loads a template and renders it with the current context. This is a way of |
| 773 |
"including" other templates within a template. |
| 774 |
|
| 775 |
The template name can either be a variable or a hard-coded (quoted) string, |
| 776 |
in either single or double quotes. |
| 777 |
|
| 778 |
This example includes the contents of the template ``"foo/bar.html"``: |
| 779 |
|
| 780 |
.. code-block:: html+django |
| 781 |
|
| 782 |
{% include "foo/bar.html" %} |
| 783 |
|
| 784 |
Normally the template name is relative to the template loader's root directory. |
| 785 |
A string argument may also be a relative path starting with ``./`` or ``../`` |
| 786 |
as described in the :ttag:`extends` tag. |
| 787 |
|
| 788 |
This example includes the contents of the template whose name is contained in |
| 789 |
the variable ``template_name``: |
| 790 |
|
| 791 |
.. code-block:: html+django |
| 792 |
|
| 793 |
{% include template_name %} |
| 794 |
|
| 795 |
The variable may also be any object with a ``render()`` method that accepts a |
| 796 |
context. This allows you to reference a compiled ``Template`` in your context. |
| 797 |
|
| 798 |
Additionally, the variable may be an iterable of template names, in which case |
| 799 |
the first that can be loaded will be used, as per |
| 800 |
:func:`~django.template.loader.select_template`. |
| 801 |
|
| 802 |
An included template is rendered within the context of the template that |
| 803 |
includes it. This example produces the output ``"Hello, John!"``: |
| 804 |
|
| 805 |
* Context: variable ``person`` is set to ``"John"`` and variable ``greeting`` |
| 806 |
is set to ``"Hello"``. |
| 807 |
|
| 808 |
* Template: |
| 809 |
|
| 810 |
.. code-block:: html+django |
| 811 |
|
| 812 |
{% include "name_snippet.html" %} |
| 813 |
|
| 814 |
* The ``name_snippet.html`` template: |
| 815 |
|
| 816 |
.. code-block:: html+django |
| 817 |
|
| 818 |
{{ greeting }}, {{ person|default:"friend" }}! |
| 819 |
|
| 820 |
You can pass additional context to the template using keyword arguments: |
| 821 |
|
| 822 |
.. code-block:: html+django |
| 823 |
|
| 824 |
{% include "name_snippet.html" with person="Jane" greeting="Hello" %} |
| 825 |
|
| 826 |
If you want to render the context only with the variables provided (or even |
| 827 |
no variables at all), use the ``only`` option. No other variables are |
| 828 |
available to the included template: |
| 829 |
|
| 830 |
.. code-block:: html+django |
| 831 |
|
| 832 |
{% include "name_snippet.html" with greeting="Hi" only %} |
| 833 |
|
| 834 |
.. note:: |
| 835 |
The :ttag:`include` tag should be considered as an implementation of |
| 836 |
"render this subtemplate and include the HTML", not as "parse this |
| 837 |
subtemplate and include its contents as if it were part of the parent". |
| 838 |
This means that there is no shared state between included templates -- |
| 839 |
each include is a completely independent rendering process. |
| 840 |
|
| 841 |
Blocks are evaluated *before* they are included. This means that a template |
| 842 |
that includes blocks from another will contain blocks that have *already |
| 843 |
been evaluated and rendered* - not blocks that can be overridden by, for |
| 844 |
example, an extending template. |
| 845 |
|
| 846 |
.. templatetag:: load |
| 847 |
|
| 848 |
``load`` |
| 849 |
-------- |
| 850 |
|
| 851 |
Loads a custom template tag set. |
| 852 |
|
| 853 |
For example, the following template would load all the tags and filters |
| 854 |
registered in ``somelibrary`` and ``otherlibrary`` located in package |
| 855 |
``package``: |
| 856 |
|
| 857 |
.. code-block:: html+django |
| 858 |
|
| 859 |
{% load somelibrary package.otherlibrary %} |
| 860 |
|
| 861 |
You can also selectively load individual filters or tags from a library, using |
| 862 |
the ``from`` argument. In this example, the template tags/filters named ``foo`` |
| 863 |
and ``bar`` will be loaded from ``somelibrary``: |
| 864 |
|
| 865 |
.. code-block:: html+django |
| 866 |
|
| 867 |
{% load foo bar from somelibrary %} |
| 868 |
|
| 869 |
See :doc:`Custom tag and filter libraries </howto/custom-template-tags>` for |
| 870 |
more information. |
| 871 |
|
| 872 |
.. templatetag:: lorem |
| 873 |
|
| 874 |
``lorem`` |
| 875 |
--------- |
| 876 |
|
| 877 |
Displays random "lorem ipsum" Latin text. This is useful for providing sample |
| 878 |
data in templates. |
| 879 |
|
| 880 |
Usage: |
| 881 |
|
| 882 |
.. code-block:: html+django |
| 883 |
|
| 884 |
{% lorem [count] [method] [random] %} |
| 885 |
|
| 886 |
The ``{% lorem %}`` tag can be used with zero, one, two or three arguments. |
| 887 |
The arguments are: |
| 888 |
|
| 889 |
=========== ============================================================= |
| 890 |
Argument Description |
| 891 |
=========== ============================================================= |
| 892 |
``count`` A number (or variable) containing the number of paragraphs or |
| 893 |
words to generate (default is 1). |
| 894 |
``method`` Either ``w`` for words, ``p`` for HTML paragraphs or ``b`` |
| 895 |
for plain-text paragraph blocks (default is ``b``). |
| 896 |
``random`` The word ``random``, which if given, does not use the common |
| 897 |
paragraph ("Lorem ipsum dolor sit amet...") when generating |
| 898 |
text. |
| 899 |
=========== ============================================================= |
| 900 |
|
| 901 |
Examples: |
| 902 |
|
| 903 |
* ``{% lorem %}`` will output the common "lorem ipsum" paragraph. |
| 904 |
* ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph |
| 905 |
and two random paragraphs each wrapped in HTML ``<p>`` tags. |
| 906 |
* ``{% lorem 2 w random %}`` will output two random Latin words. |
| 907 |
|
| 908 |
.. templatetag:: now |
| 909 |
|
| 910 |
``now`` |
| 911 |
------- |
| 912 |
|
| 913 |
Displays the current date and/or time, using a format according to the given |
| 914 |
string. Such string can contain format specifiers characters as described |
| 915 |
in the :tfilter:`date` filter section. |
| 916 |
|
| 917 |
Example: |
| 918 |
|
| 919 |
.. code-block:: html+django |
| 920 |
|
| 921 |
It is {% now "jS F Y H:i" %} |
| 922 |
|
| 923 |
Note that you can backslash-escape a format string if you want to use the |
| 924 |
"raw" value. In this example, both "o" and "f" are backslash-escaped, because |
| 925 |
otherwise each is a format string that displays the year and the time, |
| 926 |
respectively: |
| 927 |
|
| 928 |
.. code-block:: html+django |
| 929 |
|
| 930 |
It is the {% now "jS \o\f F" %} |
| 931 |
|
| 932 |
This would display as "It is the 4th of September". |
| 933 |
|
| 934 |
.. note:: |
| 935 |
|
| 936 |
The format passed can also be one of the predefined ones |
| 937 |
:setting:`DATE_FORMAT`, :setting:`DATETIME_FORMAT`, |
| 938 |
:setting:`SHORT_DATE_FORMAT` or :setting:`SHORT_DATETIME_FORMAT`. |
| 939 |
The predefined formats may vary depending on the current locale and |
| 940 |
if :doc:`/topics/i18n/formatting` is enabled, e.g.: |
| 941 |
|
| 942 |
.. code-block:: html+django |
| 943 |
|
| 944 |
It is {% now "SHORT_DATETIME_FORMAT" %} |
| 945 |
|
| 946 |
You can also use the syntax ``{% now "Y" as current_year %}`` to store the |
| 947 |
output (as a string) inside a variable. This is useful if you want to use |
| 948 |
``{% now %}`` inside a template tag like :ttag:`blocktranslate` for example: |
| 949 |
|
| 950 |
.. code-block:: html+django |
| 951 |
|
| 952 |
{% now "Y" as current_year %} |
| 953 |
{% blocktranslate %}Copyright {{ current_year }}{% endblocktranslate %} |
| 954 |
|
| 955 |
.. templatetag:: querystring |
| 956 |
|
| 957 |
``querystring`` |
| 958 |
---------------- |
| 959 |
|
| 960 |
.. versionadded:: 5.1 |
| 961 |
|
| 962 |
Outputs a URL-encoded formatted query string based on the provided parameters. |
| 963 |
|
| 964 |
This tag requires a :class:`~django.http.QueryDict` instance, which defaults to |
| 965 |
:attr:`request.GET <django.http.HttpRequest.GET>` if none is provided. |
| 966 |
|
| 967 |
If the :class:`~django.http.QueryDict` is empty and no additional parameters |
| 968 |
are provided, an empty string is returned. Otherwise, the result includes a |
| 969 |
leading ``"?"``. |
| 970 |
|
| 971 |
.. admonition:: Using ``request.GET`` as default |
| 972 |
|
| 973 |
To use ``request.GET`` as the default ``QueryDict`` instance, the |
| 974 |
``django.template.context_processors.request`` context processor should be |
| 975 |
enabled. If it's not enabled, you must either explicitly pass the |
| 976 |
``request`` object into the template context, or provide a ``QueryDict`` |
| 977 |
instance to this tag. |
| 978 |
|
| 979 |
Basic usage |
| 980 |
~~~~~~~~~~~ |
| 981 |
|
| 982 |
.. code-block:: html+django |
| 983 |
|
| 984 |
{% querystring %} |
| 985 |
|
| 986 |
Outputs the current query string verbatim. So if the query string is |
| 987 |
``?color=green``, the output would be ``?color=green``. |
| 988 |
|
| 989 |
.. code-block:: html+django |
| 990 |
|
| 991 |
{% querystring size="M" %} |
| 992 |
|
| 993 |
Outputs the current query string with the addition of the ``size`` parameter. |
| 994 |
Following the previous example, the output would be ``?color=green&size=M``. |
| 995 |
|
| 996 |
Custom QueryDict |
| 997 |
~~~~~~~~~~~~~~~~ |
| 998 |
|
| 999 |
.. code-block:: html+django |
| 1000 |
|
| 1001 |
{% querystring my_query_dict %} |
| 1002 |
|
| 1003 |
You can provide a custom ``QueryDict`` to be used instead of ``request.GET``. |
| 1004 |
So if ``my_query_dict`` is ``<QueryDict: {'color': ['blue']}>``, this outputs |
| 1005 |
``?color=blue``. |
| 1006 |
|
| 1007 |
Setting items |
| 1008 |
~~~~~~~~~~~~~ |
| 1009 |
|
| 1010 |
.. code-block:: html+django |
| 1011 |
|
| 1012 |
{% querystring color="red" size="S" %} |
| 1013 |
|
| 1014 |
Adds or modifies parameters in the query string. Each keyword argument will be |
| 1015 |
added to the query string, replacing any existing value for that key. For |
| 1016 |
instance, if the current query string is ``?color=green``, the output will be |
| 1017 |
``?color=red&size=S``. |
| 1018 |
|
| 1019 |
Removing items |
| 1020 |
~~~~~~~~~~~~~~ |
| 1021 |
|
| 1022 |
.. code-block:: html+django |
| 1023 |
|
| 1024 |
{% querystring color=None %} |
| 1025 |
|
| 1026 |
Passing ``None`` as the value removes the parameter from the query string. For |
| 1027 |
example, if the current query string is ``?color=green&size=M``, the output |
| 1028 |
will be ``?size=M``. |
| 1029 |
|
| 1030 |
Handling lists |
| 1031 |
~~~~~~~~~~~~~~ |
| 1032 |
|
| 1033 |
.. code-block:: html+django |
| 1034 |
|
| 1035 |
{% querystring color=my_list %} |
| 1036 |
|
| 1037 |
If ``my_list`` is ``["red", "blue"]``, the output will be |
| 1038 |
``?color=red&color=blue``, preserving the list structure in the query string. |
| 1039 |
|
| 1040 |
Dynamic usage |
| 1041 |
~~~~~~~~~~~~~ |
| 1042 |
|
| 1043 |
A common example of using this tag is to preserve the current query string when |
| 1044 |
displaying a page of results, while adding a link to the next and previous |
| 1045 |
pages of results. For example, if the paginator is currently on page 3, and the |
| 1046 |
current query string is ``?color=blue&size=M&page=3``, the following code would |
| 1047 |
output ``?color=blue&size=M&page=4``: |
| 1048 |
|
| 1049 |
.. code-block:: html+django |
| 1050 |
|
| 1051 |
{% querystring page=page.next_page_number %} |
| 1052 |
|
| 1053 |
You can also store the value in a variable. For example, if you need multiple |
| 1054 |
links to the same page, define it as: |
| 1055 |
|
| 1056 |
.. code-block:: html+django |
| 1057 |
|
| 1058 |
{% querystring page=page.next_page_number as next_page %} |
| 1059 |
|
| 1060 |
.. templatetag:: regroup |
| 1061 |
|
| 1062 |
``regroup`` |
| 1063 |
----------- |
| 1064 |
|
| 1065 |
Regroups a list of alike objects by a common attribute. |
| 1066 |
|
| 1067 |
This complex tag is best illustrated by way of an example: say that ``cities`` |
| 1068 |
is a list of cities represented by dictionaries containing ``"name"``, |
| 1069 |
``"population"``, and ``"country"`` keys: |
| 1070 |
|
| 1071 |
.. code-block:: python |
| 1072 |
|
| 1073 |
cities = [ |
| 1074 |
{"name": "Mumbai", "population": "19,000,000", "country": "India"}, |
| 1075 |
{"name": "Calcutta", "population": "15,000,000", "country": "India"}, |
| 1076 |
{"name": "New York", "population": "20,000,000", "country": "USA"}, |
| 1077 |
{"name": "Chicago", "population": "7,000,000", "country": "USA"}, |
| 1078 |
{"name": "Tokyo", "population": "33,000,000", "country": "Japan"}, |
| 1079 |
] |
| 1080 |
|
| 1081 |
...and you'd like to display a hierarchical list that is ordered by country, |
| 1082 |
like this: |
| 1083 |
|
| 1084 |
* India |
| 1085 |
|
| 1086 |
* Mumbai: 19,000,000 |
| 1087 |
* Calcutta: 15,000,000 |
| 1088 |
|
| 1089 |
* USA |
| 1090 |
|
| 1091 |
* New York: 20,000,000 |
| 1092 |
* Chicago: 7,000,000 |
| 1093 |
|
| 1094 |
* Japan |
| 1095 |
|
| 1096 |
* Tokyo: 33,000,000 |
| 1097 |
|
| 1098 |
You can use the ``{% regroup %}`` tag to group the list of cities by country. |
| 1099 |
The following snippet of template code would accomplish this: |
| 1100 |
|
| 1101 |
.. code-block:: html+django |
| 1102 |
|
| 1103 |
{% regroup cities by country as country_list %} |
| 1104 |
|
| 1105 |
<ul> |
| 1106 |
{% for country in country_list %} |
| 1107 |
<li>{{ country.grouper }} |
| 1108 |
<ul> |
| 1109 |
{% for city in country.list %} |
| 1110 |
<li>{{ city.name }}: {{ city.population }}</li> |
| 1111 |
{% endfor %} |
| 1112 |
</ul> |
| 1113 |
</li> |
| 1114 |
{% endfor %} |
| 1115 |
</ul> |
| 1116 |
|
| 1117 |
Let's walk through this example. ``{% regroup %}`` takes three arguments: the |
| 1118 |
list you want to regroup, the attribute to group by, and the name of the |
| 1119 |
resulting list. Here, we're regrouping the ``cities`` list by the ``country`` |
| 1120 |
attribute and calling the result ``country_list``. |
| 1121 |
|
| 1122 |
``{% regroup %}`` produces a list (in this case, ``country_list``) of |
| 1123 |
**group objects**. Group objects are instances of |
| 1124 |
:py:func:`~collections.namedtuple` with two fields: |
| 1125 |
|
| 1126 |
* ``grouper`` -- the item that was grouped by (e.g., the string "India" or |
| 1127 |
"Japan"). |
| 1128 |
* ``list`` -- a list of all items in this group (e.g., a list of all cities |
| 1129 |
with country='India'). |
| 1130 |
|
| 1131 |
Because ``{% regroup %}`` produces :py:func:`~collections.namedtuple` objects, |
| 1132 |
you can also write the previous example as: |
| 1133 |
|
| 1134 |
.. code-block:: html+django |
| 1135 |
|
| 1136 |
{% regroup cities by country as country_list %} |
| 1137 |
|
| 1138 |
<ul> |
| 1139 |
{% for country, local_cities in country_list %} |
| 1140 |
<li>{{ country }} |
| 1141 |
<ul> |
| 1142 |
{% for city in local_cities %} |
| 1143 |
<li>{{ city.name }}: {{ city.population }}</li> |
| 1144 |
{% endfor %} |
| 1145 |
</ul> |
| 1146 |
</li> |
| 1147 |
{% endfor %} |
| 1148 |
</ul> |
| 1149 |
|
| 1150 |
Note that ``{% regroup %}`` does not order its input! Our example relies on |
| 1151 |
the fact that the ``cities`` list was ordered by ``country`` in the first place. |
| 1152 |
If the ``cities`` list did *not* order its members by ``country``, the |
| 1153 |
regrouping would naively display more than one group for a single country. For |
| 1154 |
example, say the ``cities`` list was set to this (note that the countries are not |
| 1155 |
grouped together): |
| 1156 |
|
| 1157 |
.. code-block:: python |
| 1158 |
|
| 1159 |
cities = [ |
| 1160 |
{"name": "Mumbai", "population": "19,000,000", "country": "India"}, |
| 1161 |
{"name": "New York", "population": "20,000,000", "country": "USA"}, |
| 1162 |
{"name": "Calcutta", "population": "15,000,000", "country": "India"}, |
| 1163 |
{"name": "Chicago", "population": "7,000,000", "country": "USA"}, |
| 1164 |
{"name": "Tokyo", "population": "33,000,000", "country": "Japan"}, |
| 1165 |
] |
| 1166 |
|
| 1167 |
With this input for ``cities``, the example ``{% regroup %}`` template code |
| 1168 |
above would result in the following output: |
| 1169 |
|
| 1170 |
* India |
| 1171 |
|
| 1172 |
* Mumbai: 19,000,000 |
| 1173 |
|
| 1174 |
* USA |
| 1175 |
|
| 1176 |
* New York: 20,000,000 |
| 1177 |
|
| 1178 |
* India |
| 1179 |
|
| 1180 |
* Calcutta: 15,000,000 |
| 1181 |
|
| 1182 |
* USA |
| 1183 |
|
| 1184 |
* Chicago: 7,000,000 |
| 1185 |
|
| 1186 |
* Japan |
| 1187 |
|
| 1188 |
* Tokyo: 33,000,000 |
| 1189 |
|
| 1190 |
The easiest solution to this gotcha is to make sure in your view code that the |
| 1191 |
data is ordered according to how you want to display it. |
| 1192 |
|
| 1193 |
Another solution is to sort the data in the template using the |
| 1194 |
:tfilter:`dictsort` filter, if your data is in a list of dictionaries: |
| 1195 |
|
| 1196 |
.. code-block:: html+django |
| 1197 |
|
| 1198 |
{% regroup cities|dictsort:"country" by country as country_list %} |
| 1199 |
|
| 1200 |
Grouping on other properties |
| 1201 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1202 |
|
| 1203 |
Any valid template lookup is a legal grouping attribute for the regroup |
| 1204 |
tag, including methods, attributes, dictionary keys and list items. For |
| 1205 |
example, if the "country" field is a foreign key to a class with |
| 1206 |
an attribute "description," you could use: |
| 1207 |
|
| 1208 |
.. code-block:: html+django |
| 1209 |
|
| 1210 |
{% regroup cities by country.description as country_list %} |
| 1211 |
|
| 1212 |
Or, if ``country`` is a field with ``choices``, it will have a |
| 1213 |
:meth:`~django.db.models.Model.get_FOO_display` method available as an |
| 1214 |
attribute, allowing you to group on the display string rather than the |
| 1215 |
``choices`` key: |
| 1216 |
|
| 1217 |
.. code-block:: html+django |
| 1218 |
|
| 1219 |
{% regroup cities by get_country_display as country_list %} |
| 1220 |
|
| 1221 |
``{{ country.grouper }}`` will now display the value fields from the |
| 1222 |
``choices`` set rather than the keys. |
| 1223 |
|
| 1224 |
.. templatetag:: resetcycle |
| 1225 |
|
| 1226 |
``resetcycle`` |
| 1227 |
-------------- |
| 1228 |
|
| 1229 |
Resets a previous `cycle`_ so that it restarts from its first item at its next |
| 1230 |
encounter. Without arguments, ``{% resetcycle %}`` will reset the last |
| 1231 |
``{% cycle %}`` defined in the template. |
| 1232 |
|
| 1233 |
Example usage: |
| 1234 |
|
| 1235 |
.. code-block:: html+django |
| 1236 |
|
| 1237 |
{% for coach in coach_list %} |
| 1238 |
<h1>{{ coach.name }}</h1> |
| 1239 |
{% for athlete in coach.athlete_set.all %} |
| 1240 |
<p class="{% cycle 'odd' 'even' %}">{{ athlete.name }}</p> |
| 1241 |
{% endfor %} |
| 1242 |
{% resetcycle %} |
| 1243 |
{% endfor %} |
| 1244 |
|
| 1245 |
This example would return this HTML: |
| 1246 |
|
| 1247 |
.. code-block:: html |
| 1248 |
|
| 1249 |
<h1>Gareth</h1> |
| 1250 |
<p class="odd">Harry</p> |
| 1251 |
<p class="even">John</p> |
| 1252 |
<p class="odd">Nick</p> |
| 1253 |
|
| 1254 |
<h1>John</h1> |
| 1255 |
<p class="odd">Andrea</p> |
| 1256 |
<p class="even">Melissa</p> |
| 1257 |
|
| 1258 |
Notice how the first block ends with ``class="odd"`` and the new one starts |
| 1259 |
with ``class="odd"``. Without the ``{% resetcycle %}`` tag, the second block |
| 1260 |
would start with ``class="even"``. |
| 1261 |
|
| 1262 |
You can also reset named cycle tags: |
| 1263 |
|
| 1264 |
.. code-block:: html+django |
| 1265 |
|
| 1266 |
{% for item in list %} |
| 1267 |
<p class="{% cycle 'odd' 'even' as stripe %} {% cycle 'major' 'minor' 'minor' 'minor' 'minor' as tick %}"> |
| 1268 |
{{ item.data }} |
| 1269 |
</p> |
| 1270 |
{% ifchanged item.category %} |
| 1271 |
<h1>{{ item.category }}</h1> |
| 1272 |
{% if not forloop.first %}{% resetcycle tick %}{% endif %} |
| 1273 |
{% endifchanged %} |
| 1274 |
{% endfor %} |
| 1275 |
|
| 1276 |
In this example, we have both the alternating odd/even rows and a "major" row |
| 1277 |
every fifth row. Only the five-row cycle is reset when a category changes. |
| 1278 |
|
| 1279 |
.. templatetag:: spaceless |
| 1280 |
|
| 1281 |
``spaceless`` |
| 1282 |
------------- |
| 1283 |
|
| 1284 |
Removes whitespace between HTML tags. This includes tab |
| 1285 |
characters and newlines. |
| 1286 |
|
| 1287 |
Example usage: |
| 1288 |
|
| 1289 |
.. code-block:: html+django |
| 1290 |
|
| 1291 |
{% spaceless %} |
| 1292 |
<p> |
| 1293 |
<a href="foo/">Foo</a> |
| 1294 |
</p> |
| 1295 |
{% endspaceless %} |
| 1296 |
|
| 1297 |
This example would return this HTML: |
| 1298 |
|
| 1299 |
.. code-block:: html+django |
| 1300 |
|
| 1301 |
<p><a href="foo/">Foo</a></p> |
| 1302 |
|
| 1303 |
Only space between *tags* is removed -- not space between tags and text. In |
| 1304 |
this example, the space around ``Hello`` won't be stripped: |
| 1305 |
|
| 1306 |
.. code-block:: html+django |
| 1307 |
|
| 1308 |
{% spaceless %} |
| 1309 |
<strong> |
| 1310 |
Hello |
| 1311 |
</strong> |
| 1312 |
{% endspaceless %} |
| 1313 |
|
| 1314 |
.. templatetag:: templatetag |
| 1315 |
|
| 1316 |
``templatetag`` |
| 1317 |
--------------- |
| 1318 |
|
| 1319 |
Outputs one of the syntax characters used to compose template tags. |
| 1320 |
|
| 1321 |
The template system has no concept of "escaping" individual characters. |
| 1322 |
However, you can use the ``{% templatetag %}`` tag to display one of the |
| 1323 |
template tag character combinations. |
| 1324 |
|
| 1325 |
The argument tells which template bit to output: |
| 1326 |
|
| 1327 |
================== ======= |
| 1328 |
Argument Outputs |
| 1329 |
================== ======= |
| 1330 |
``openblock`` ``{%`` |
| 1331 |
``closeblock`` ``%}`` |
| 1332 |
``openvariable`` ``{{`` |
| 1333 |
``closevariable`` ``}}`` |
| 1334 |
``openbrace`` ``{`` |
| 1335 |
``closebrace`` ``}`` |
| 1336 |
``opencomment`` ``{#`` |
| 1337 |
``closecomment`` ``#}`` |
| 1338 |
================== ======= |
| 1339 |
|
| 1340 |
Sample usage: |
| 1341 |
|
| 1342 |
.. code-block:: html+django |
| 1343 |
|
| 1344 |
The {% templatetag openblock %} characters open a block. |
| 1345 |
|
| 1346 |
See also the :ttag:`verbatim` tag for another way of including these |
| 1347 |
characters. |
| 1348 |
|
| 1349 |
.. templatetag:: url |
| 1350 |
|
| 1351 |
``url`` |
| 1352 |
------- |
| 1353 |
|
| 1354 |
Returns an absolute path reference (a URL without the domain name) matching a |
| 1355 |
given view and optional parameters. Any special characters in the resulting |
| 1356 |
path will be encoded using :func:`~django.utils.encoding.iri_to_uri`. |
| 1357 |
|
| 1358 |
This is a way to output links without violating the DRY principle by having to |
| 1359 |
hard-code URLs in your templates: |
| 1360 |
|
| 1361 |
.. code-block:: html+django |
| 1362 |
|
| 1363 |
{% url 'some-url-name' v1 v2 %} |
| 1364 |
|
| 1365 |
The first argument is a :ref:`URL pattern name <naming-url-patterns>`. It can |
| 1366 |
be a quoted literal or any other context variable. Additional arguments are |
| 1367 |
optional and should be space-separated values that will be used as arguments in |
| 1368 |
the URL. The example above shows passing positional arguments. Alternatively |
| 1369 |
you may use keyword syntax: |
| 1370 |
|
| 1371 |
.. code-block:: html+django |
| 1372 |
|
| 1373 |
{% url 'some-url-name' arg1=v1 arg2=v2 %} |
| 1374 |
|
| 1375 |
Do not mix both positional and keyword syntax in a single call. All arguments |
| 1376 |
required by the URLconf should be present. |
| 1377 |
|
| 1378 |
For example, suppose you have a view, ``app_views.client``, whose URLconf |
| 1379 |
takes a client ID (here, ``client()`` is a method inside the views file |
| 1380 |
``app_views.py``). The URLconf line might look like this: |
| 1381 |
|
| 1382 |
.. code-block:: python |
| 1383 |
|
| 1384 |
path("client/<int:id>/", app_views.client, name="app-views-client") |
| 1385 |
|
| 1386 |
If this app's URLconf is included into the project's URLconf under a path |
| 1387 |
such as this: |
| 1388 |
|
| 1389 |
.. code-block:: python |
| 1390 |
|
| 1391 |
path("clients/", include("project_name.app_name.urls")) |
| 1392 |
|
| 1393 |
...then, in a template, you can create a link to this view like this: |
| 1394 |
|
| 1395 |
.. code-block:: html+django |
| 1396 |
|
| 1397 |
{% url 'app-views-client' client.id %} |
| 1398 |
|
| 1399 |
The template tag will output the string ``/clients/client/123/``. |
| 1400 |
|
| 1401 |
Note that if the URL you're reversing doesn't exist, you'll get an |
| 1402 |
:exc:`~django.urls.NoReverseMatch` exception raised, which will cause your |
| 1403 |
site to display an error page. |
| 1404 |
|
| 1405 |
If you'd like to retrieve a URL without displaying it, you can use a slightly |
| 1406 |
different call: |
| 1407 |
|
| 1408 |
.. code-block:: html+django |
| 1409 |
|
| 1410 |
{% url 'some-url-name' arg arg2 as the_url %} |
| 1411 |
|
| 1412 |
<a href="{{ the_url }}">I'm linking to {{ the_url }}</a> |
| 1413 |
|
| 1414 |
The scope of the variable created by the ``as var`` syntax is the |
| 1415 |
``{% block %}`` in which the ``{% url %}`` tag appears. |
| 1416 |
|
| 1417 |
This ``{% url ... as var %}`` syntax will *not* cause an error if the view is |
| 1418 |
missing. In practice you'll use this to link to views that are optional: |
| 1419 |
|
| 1420 |
.. code-block:: html+django |
| 1421 |
|
| 1422 |
{% url 'some-url-name' as the_url %} |
| 1423 |
{% if the_url %} |
| 1424 |
<a href="{{ the_url }}">Link to optional stuff</a> |
| 1425 |
{% endif %} |
| 1426 |
|
| 1427 |
If you'd like to retrieve a namespaced URL, specify the fully qualified name: |
| 1428 |
|
| 1429 |
.. code-block:: html+django |
| 1430 |
|
| 1431 |
{% url 'myapp:view-name' %} |
| 1432 |
|
| 1433 |
This will follow the normal :ref:`namespaced URL resolution strategy |
| 1434 |
<topics-http-reversing-url-namespaces>`, including using any hints provided |
| 1435 |
by the context as to the current application. |
| 1436 |
|
| 1437 |
.. warning:: |
| 1438 |
|
| 1439 |
Don't forget to put quotes around the URL pattern ``name``, otherwise the |
| 1440 |
value will be interpreted as a context variable! |
| 1441 |
|
| 1442 |
.. templatetag:: verbatim |
| 1443 |
|
| 1444 |
``verbatim`` |
| 1445 |
------------ |
| 1446 |
|
| 1447 |
Stops the template engine from rendering the contents of this block tag. |
| 1448 |
|
| 1449 |
A common use is to allow a JavaScript template layer that collides with |
| 1450 |
Django's syntax. For example: |
| 1451 |
|
| 1452 |
.. code-block:: html+django |
| 1453 |
|
| 1454 |
{% verbatim %} |
| 1455 |
{{if dying}}Still alive.{{/if}} |
| 1456 |
{% endverbatim %} |
| 1457 |
|
| 1458 |
You can also designate a specific closing tag, allowing the use of |
| 1459 |
``{% endverbatim %}`` as part of the unrendered contents: |
| 1460 |
|
| 1461 |
.. code-block:: html+django |
| 1462 |
|
| 1463 |
{% verbatim myblock %} |
| 1464 |
Avoid template rendering via the {% verbatim %}{% endverbatim %} block. |
| 1465 |
{% endverbatim myblock %} |
| 1466 |
|
| 1467 |
.. templatetag:: widthratio |
| 1468 |
|
| 1469 |
``widthratio`` |
| 1470 |
-------------- |
| 1471 |
|
| 1472 |
For creating bar charts and such, this tag calculates the ratio of a given |
| 1473 |
value to a maximum value, and then applies that ratio to a constant. |
| 1474 |
|
| 1475 |
For example: |
| 1476 |
|
| 1477 |
.. code-block:: html+django |
| 1478 |
|
| 1479 |
<img src="bar.png" alt="Bar" |
| 1480 |
height="10" width="{% widthratio this_value max_value max_width %}"> |
| 1481 |
|
| 1482 |
If ``this_value`` is 175, ``max_value`` is 200, and ``max_width`` is 100, the |
| 1483 |
image in the above example will be 88 pixels wide |
| 1484 |
(because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88). |
| 1485 |
|
| 1486 |
In some cases you might want to capture the result of ``widthratio`` in a |
| 1487 |
variable. It can be useful, for instance, in a :ttag:`blocktranslate` like this: |
| 1488 |
|
| 1489 |
.. code-block:: html+django |
| 1490 |
|
| 1491 |
{% widthratio this_value max_value max_width as width %} |
| 1492 |
{% blocktranslate %}The width is: {{ width }}{% endblocktranslate %} |
| 1493 |
|
| 1494 |
.. templatetag:: with |
| 1495 |
|
| 1496 |
``with`` |
| 1497 |
-------- |
| 1498 |
|
| 1499 |
Caches a complex variable under a simpler name. This is useful when accessing |
| 1500 |
an "expensive" method (e.g., one that hits the database) multiple times. |
| 1501 |
|
| 1502 |
For example: |
| 1503 |
|
| 1504 |
.. code-block:: html+django |
| 1505 |
|
| 1506 |
{% with total=business.employees.count %} |
| 1507 |
{{ total }} employee{{ total|pluralize }} |
| 1508 |
{% endwith %} |
| 1509 |
|
| 1510 |
The populated variable (in the example above, ``total``) is only available |
| 1511 |
between the ``{% with %}`` and ``{% endwith %}`` tags. |
| 1512 |
|
| 1513 |
You can assign more than one context variable: |
| 1514 |
|
| 1515 |
.. code-block:: html+django |
| 1516 |
|
| 1517 |
{% with alpha=1 beta=2 %} |
| 1518 |
... |
| 1519 |
{% endwith %} |
| 1520 |
|
| 1521 |
.. note:: The previous more verbose format is still supported: |
| 1522 |
``{% with business.employees.count as total %}`` |
| 1523 |
|
| 1524 |
.. _ref-templates-builtins-filters: |
| 1525 |
|
| 1526 |
Built-in filter reference |
| 1527 |
========================= |
| 1528 |
|
| 1529 |
.. templatefilter:: add |
| 1530 |
|
| 1531 |
``add`` |
| 1532 |
------- |
| 1533 |
|
| 1534 |
Adds the argument to the value. |
| 1535 |
|
| 1536 |
For example: |
| 1537 |
|
| 1538 |
.. code-block:: html+django |
| 1539 |
|
| 1540 |
{{ value|add:"2" }} |
| 1541 |
|
| 1542 |
If ``value`` is ``4``, then the output will be ``6``. |
| 1543 |
|
| 1544 |
This filter will first try to coerce both values to integers. If this fails, |
| 1545 |
it'll attempt to add the values together anyway. This will work on some data |
| 1546 |
types (strings, list, etc.) and fail on others. If it fails, the result will |
| 1547 |
be an empty string. |
| 1548 |
|
| 1549 |
For example, if we have: |
| 1550 |
|
| 1551 |
.. code-block:: html+django |
| 1552 |
|
| 1553 |
{{ first|add:second }} |
| 1554 |
|
| 1555 |
and ``first`` is ``[1, 2, 3]`` and ``second`` is ``[4, 5, 6]``, then the |
| 1556 |
output will be ``[1, 2, 3, 4, 5, 6]``. |
| 1557 |
|
| 1558 |
.. warning:: |
| 1559 |
|
| 1560 |
Strings that can be coerced to integers will be **summed**, not |
| 1561 |
concatenated, as in the first example above. |
| 1562 |
|
| 1563 |
.. templatefilter:: addslashes |
| 1564 |
|
| 1565 |
``addslashes`` |
| 1566 |
-------------- |
| 1567 |
|
| 1568 |
Adds slashes before quotes. Useful for escaping strings in CSV, for example. |
| 1569 |
|
| 1570 |
For example: |
| 1571 |
|
| 1572 |
.. code-block:: html+django |
| 1573 |
|
| 1574 |
{{ value|addslashes }} |
| 1575 |
|
| 1576 |
If ``value`` is ``"I'm using Django"``, the output will be |
| 1577 |
``"I\'m using Django"``. |
| 1578 |
|
| 1579 |
.. templatefilter:: capfirst |
| 1580 |
|
| 1581 |
``capfirst`` |
| 1582 |
------------ |
| 1583 |
|
| 1584 |
Capitalizes the first character of the value. If the first character is not |
| 1585 |
a letter, this filter has no effect. |
| 1586 |
|
| 1587 |
For example: |
| 1588 |
|
| 1589 |
.. code-block:: html+django |
| 1590 |
|
| 1591 |
{{ value|capfirst }} |
| 1592 |
|
| 1593 |
If ``value`` is ``"django"``, the output will be ``"Django"``. |
| 1594 |
|
| 1595 |
.. templatefilter:: center |
| 1596 |
|
| 1597 |
``center`` |
| 1598 |
---------- |
| 1599 |
|
| 1600 |
Centers the value in a field of a given width. |
| 1601 |
|
| 1602 |
For example: |
| 1603 |
|
| 1604 |
.. code-block:: html+django |
| 1605 |
|
| 1606 |
"{{ value|center:"15" }}" |
| 1607 |
|
| 1608 |
If ``value`` is ``"Django"``, the output will be ``" Django "``. |
| 1609 |
|
| 1610 |
.. templatefilter:: cut |
| 1611 |
|
| 1612 |
``cut`` |
| 1613 |
------- |
| 1614 |
|
| 1615 |
Removes all values of arg from the given string. |
| 1616 |
|
| 1617 |
For example: |
| 1618 |
|
| 1619 |
.. code-block:: html+django |
| 1620 |
|
| 1621 |
{{ value|cut:" " }} |
| 1622 |
|
| 1623 |
If ``value`` is ``"String with spaces"``, the output will be |
| 1624 |
``"Stringwithspaces"``. |
| 1625 |
|
| 1626 |
.. templatefilter:: date |
| 1627 |
|
| 1628 |
``date`` |
| 1629 |
-------- |
| 1630 |
|
| 1631 |
Formats a date according to the given format. |
| 1632 |
|
| 1633 |
Uses a similar format to PHP's `date() |
| 1634 |
<https://www.php.net/manual/en/function.date.php>`_ function with some |
| 1635 |
differences. |
| 1636 |
|
| 1637 |
.. note:: |
| 1638 |
These format characters are not used in Django outside of templates. They |
| 1639 |
were designed to be compatible with PHP to ease transitioning for designers. |
| 1640 |
|
| 1641 |
.. _date-and-time-formatting-specifiers: |
| 1642 |
|
| 1643 |
Available format strings: |
| 1644 |
|
| 1645 |
================ ======================================== ===================== |
| 1646 |
Format character Description Example output |
| 1647 |
================ ======================================== ===================== |
| 1648 |
**Day** |
| 1649 |
``d`` Day of the month, 2 digits with ``'01'`` to ``'31'`` |
| 1650 |
leading zeros. |
| 1651 |
``j`` Day of the month without leading ``'1'`` to ``'31'`` |
| 1652 |
zeros. |
| 1653 |
``D`` Day of the week, textual, 3 letters. ``'Fri'`` |
| 1654 |
``l`` Day of the week, textual, long. ``'Friday'`` |
| 1655 |
``S`` English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'`` |
| 1656 |
month, 2 characters. |
| 1657 |
``w`` Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday) |
| 1658 |
leading zeros. |
| 1659 |
``z`` Day of the year. ``1`` to ``366`` |
| 1660 |
**Week** |
| 1661 |
``W`` ISO-8601 week number of year, with ``1``, ``53`` |
| 1662 |
weeks starting on Monday. |
| 1663 |
**Month** |
| 1664 |
``m`` Month, 2 digits with leading zeros. ``'01'`` to ``'12'`` |
| 1665 |
``n`` Month without leading zeros. ``'1'`` to ``'12'`` |
| 1666 |
``M`` Month, textual, 3 letters. ``'Jan'`` |
| 1667 |
``b`` Month, textual, 3 letters, lowercase. ``'jan'`` |
| 1668 |
``E`` Month, locale specific alternative |
| 1669 |
representation usually used for long |
| 1670 |
date representation. ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``) |
| 1671 |
``F`` Month, textual, long. ``'January'`` |
| 1672 |
``N`` Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'`` |
| 1673 |
style. Proprietary extension. |
| 1674 |
``t`` Number of days in the given month. ``28`` to ``31`` |
| 1675 |
**Year** |
| 1676 |
``y`` Year, 2 digits with leading zeros. ``'00'`` to ``'99'`` |
| 1677 |
``Y`` Year, 4 digits with leading zeros. ``'0001'``, ..., ``'1999'``, ..., ``'9999'`` |
| 1678 |
``L`` Boolean for whether it's a leap year. ``True`` or ``False`` |
| 1679 |
``o`` ISO-8601 week-numbering year, ``'1999'`` |
| 1680 |
corresponding to the ISO-8601 week |
| 1681 |
number (W) which uses leap weeks. See Y |
| 1682 |
for the more common year format. |
| 1683 |
**Time** |
| 1684 |
``g`` Hour, 12-hour format without leading ``'1'`` to ``'12'`` |
| 1685 |
zeros. |
| 1686 |
``G`` Hour, 24-hour format without leading ``'0'`` to ``'23'`` |
| 1687 |
zeros. |
| 1688 |
``h`` Hour, 12-hour format. ``'01'`` to ``'12'`` |
| 1689 |
``H`` Hour, 24-hour format. ``'00'`` to ``'23'`` |
| 1690 |
``i`` Minutes. ``'00'`` to ``'59'`` |
| 1691 |
``s`` Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'`` |
| 1692 |
``u`` Microseconds. ``000000`` to ``999999`` |
| 1693 |
``a`` ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'`` |
| 1694 |
this is slightly different than PHP's |
| 1695 |
output, because this includes periods |
| 1696 |
to match Associated Press style.) |
| 1697 |
``A`` ``'AM'`` or ``'PM'``. ``'AM'`` |
| 1698 |
``f`` Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'`` |
| 1699 |
with minutes left off if they're zero. |
| 1700 |
Proprietary extension. |
| 1701 |
``P`` Time, in 12-hour hours, minutes and ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'`` |
| 1702 |
'a.m.'/'p.m.', with minutes left off |
| 1703 |
if they're zero and the special-case |
| 1704 |
strings 'midnight' and 'noon' if |
| 1705 |
appropriate. Proprietary extension. |
| 1706 |
**Timezone** |
| 1707 |
``e`` Timezone name. Could be in any format, |
| 1708 |
or might return an empty string, ``''``, ``'GMT'``, ``'-500'``, ``'US/Eastern'``, etc. |
| 1709 |
depending on the datetime. |
| 1710 |
``I`` Daylight saving time, whether it's in ``'1'`` or ``'0'`` |
| 1711 |
effect or not. |
| 1712 |
``O`` Difference to Greenwich time in hours. ``'+0200'`` |
| 1713 |
``T`` Time zone of this machine. ``'EST'``, ``'MDT'`` |
| 1714 |
``Z`` Time zone offset in seconds. The ``-43200`` to ``43200`` |
| 1715 |
offset for timezones west of UTC is |
| 1716 |
always negative, and for those east of |
| 1717 |
UTC is always positive. |
| 1718 |
**Date/Time** |
| 1719 |
``c`` ISO 8601 format. (Note: unlike other ``2008-01-02T10:30:00.000123+02:00``, |
| 1720 |
formatters, such as "Z", "O" or "r", or ``2008-01-02T10:30:00.000123`` if the datetime is naive |
| 1721 |
the "c" formatter will not add timezone |
| 1722 |
offset if value is a naive datetime |
| 1723 |
(see :class:`datetime.tzinfo`). |
| 1724 |
``r`` :rfc:`RFC 5322 <5322#section-3.3>` ``'Thu, 21 Dec 2000 16:01:07 +0200'`` |
| 1725 |
formatted date. |
| 1726 |
``U`` Seconds since the Unix Epoch |
| 1727 |
(January 1 1970 00:00:00 UTC). |
| 1728 |
================ ======================================== ===================== |
| 1729 |
|
| 1730 |
For example: |
| 1731 |
|
| 1732 |
.. code-block:: html+django |
| 1733 |
|
| 1734 |
{{ value|date:"D d M Y" }} |
| 1735 |
|
| 1736 |
If ``value`` is a :py:class:`~datetime.datetime` object (e.g., the result of |
| 1737 |
``datetime.datetime.now()``), the output will be the string |
| 1738 |
``'Wed 09 Jan 2008'``. |
| 1739 |
|
| 1740 |
The format passed can be one of the predefined ones :setting:`DATE_FORMAT`, |
| 1741 |
:setting:`DATETIME_FORMAT`, :setting:`SHORT_DATE_FORMAT` or |
| 1742 |
:setting:`SHORT_DATETIME_FORMAT`, or a custom format that uses the format |
| 1743 |
specifiers shown in the table above. Note that predefined formats may vary |
| 1744 |
depending on the current locale. |
| 1745 |
|
| 1746 |
Assuming that :setting:`LANGUAGE_CODE` is, for example, ``"es"``, then for: |
| 1747 |
|
| 1748 |
.. code-block:: html+django |
| 1749 |
|
| 1750 |
{{ value|date:"SHORT_DATE_FORMAT" }} |
| 1751 |
|
| 1752 |
the output would be the string ``"09/01/2008"`` (the ``"SHORT_DATE_FORMAT"`` |
| 1753 |
format specifier for the ``es`` locale as shipped with Django is ``"d/m/Y"``). |
| 1754 |
|
| 1755 |
When used without a format string, the ``DATE_FORMAT`` format specifier is |
| 1756 |
used. Assuming the same settings as the previous example: |
| 1757 |
|
| 1758 |
.. code-block:: html+django |
| 1759 |
|
| 1760 |
{{ value|date }} |
| 1761 |
|
| 1762 |
outputs ``9 de Enero de 2008`` (the ``DATE_FORMAT`` format specifier for the |
| 1763 |
``es`` locale is ``r'j \d\e F \d\e Y'``). Both "d" and "e" are |
| 1764 |
backslash-escaped, because otherwise each is a format string that displays the |
| 1765 |
day and the timezone name, respectively. |
| 1766 |
|
| 1767 |
You can combine ``date`` with the :tfilter:`time` filter to render a full |
| 1768 |
representation of a ``datetime`` value. E.g.: |
| 1769 |
|
| 1770 |
.. code-block:: html+django |
| 1771 |
|
| 1772 |
{{ value|date:"D d M Y" }} {{ value|time:"H:i" }} |
| 1773 |
|
| 1774 |
.. templatefilter:: default |
| 1775 |
|
| 1776 |
``default`` |
| 1777 |
----------- |
| 1778 |
|
| 1779 |
If value evaluates to ``False``, uses the given default. Otherwise, uses the |
| 1780 |
value. |
| 1781 |
|
| 1782 |
For example: |
| 1783 |
|
| 1784 |
.. code-block:: html+django |
| 1785 |
|
| 1786 |
{{ value|default:"nothing" }} |
| 1787 |
|
| 1788 |
If ``value`` is ``""`` (the empty string), the output will be ``nothing``. |
| 1789 |
|
| 1790 |
.. templatefilter:: default_if_none |
| 1791 |
|
| 1792 |
``default_if_none`` |
| 1793 |
------------------- |
| 1794 |
|
| 1795 |
If (and only if) value is ``None``, uses the given default. Otherwise, uses the |
| 1796 |
value. |
| 1797 |
|
| 1798 |
Note that if an empty string is given, the default value will *not* be used. |
| 1799 |
Use the :tfilter:`default` filter if you want to fallback for empty strings. |
| 1800 |
|
| 1801 |
For example: |
| 1802 |
|
| 1803 |
.. code-block:: html+django |
| 1804 |
|
| 1805 |
{{ value|default_if_none:"nothing" }} |
| 1806 |
|
| 1807 |
If ``value`` is ``None``, the output will be ``nothing``. |
| 1808 |
|
| 1809 |
.. templatefilter:: dictsort |
| 1810 |
|
| 1811 |
``dictsort`` |
| 1812 |
------------ |
| 1813 |
|
| 1814 |
Takes a list of dictionaries and returns that list sorted by the key given in |
| 1815 |
the argument. |
| 1816 |
|
| 1817 |
For example: |
| 1818 |
|
| 1819 |
.. code-block:: html+django |
| 1820 |
|
| 1821 |
{{ value|dictsort:"name" }} |
| 1822 |
|
| 1823 |
If ``value`` is: |
| 1824 |
|
| 1825 |
.. code-block:: python |
| 1826 |
|
| 1827 |
[ |
| 1828 |
{"name": "zed", "age": 19}, |
| 1829 |
{"name": "amy", "age": 22}, |
| 1830 |
{"name": "joe", "age": 31}, |
| 1831 |
] |
| 1832 |
|
| 1833 |
then the output would be: |
| 1834 |
|
| 1835 |
.. code-block:: python |
| 1836 |
|
| 1837 |
[ |
| 1838 |
{"name": "amy", "age": 22}, |
| 1839 |
{"name": "joe", "age": 31}, |
| 1840 |
{"name": "zed", "age": 19}, |
| 1841 |
] |
| 1842 |
|
| 1843 |
You can also do more complicated things like: |
| 1844 |
|
| 1845 |
.. code-block:: html+django |
| 1846 |
|
| 1847 |
{% for book in books|dictsort:"author.age" %} |
| 1848 |
* {{ book.title }} ({{ book.author.name }}) |
| 1849 |
{% endfor %} |
| 1850 |
|
| 1851 |
If ``books`` is: |
| 1852 |
|
| 1853 |
.. code-block:: python |
| 1854 |
|
| 1855 |
[ |
| 1856 |
{"title": "1984", "author": {"name": "George", "age": 45}}, |
| 1857 |
{"title": "Timequake", "author": {"name": "Kurt", "age": 75}}, |
| 1858 |
{"title": "Alice", "author": {"name": "Lewis", "age": 33}}, |
| 1859 |
] |
| 1860 |
|
| 1861 |
then the output would be: |
| 1862 |
|
| 1863 |
.. code-block:: html+django |
| 1864 |
|
| 1865 |
* Alice (Lewis) |
| 1866 |
* 1984 (George) |
| 1867 |
* Timequake (Kurt) |
| 1868 |
|
| 1869 |
``dictsort`` can also order a list of lists (or any other object implementing |
| 1870 |
``__getitem__()``) by elements at specified index. For example: |
| 1871 |
|
| 1872 |
.. code-block:: html+django |
| 1873 |
|
| 1874 |
{{ value|dictsort:0 }} |
| 1875 |
|
| 1876 |
If ``value`` is: |
| 1877 |
|
| 1878 |
.. code-block:: python |
| 1879 |
|
| 1880 |
[ |
| 1881 |
("a", "42"), |
| 1882 |
("c", "string"), |
| 1883 |
("b", "foo"), |
| 1884 |
] |
| 1885 |
|
| 1886 |
then the output would be: |
| 1887 |
|
| 1888 |
.. code-block:: python |
| 1889 |
|
| 1890 |
[ |
| 1891 |
("a", "42"), |
| 1892 |
("b", "foo"), |
| 1893 |
("c", "string"), |
| 1894 |
] |
| 1895 |
|
| 1896 |
You must pass the index as an integer rather than a string. The following |
| 1897 |
produce empty output: |
| 1898 |
|
| 1899 |
.. code-block:: html+django |
| 1900 |
|
| 1901 |
{{ values|dictsort:"0" }} |
| 1902 |
|
| 1903 |
Ordering by elements at specified index is not supported on dictionaries. |
| 1904 |
|
| 1905 |
.. templatefilter:: dictsortreversed |
| 1906 |
|
| 1907 |
``dictsortreversed`` |
| 1908 |
-------------------- |
| 1909 |
|
| 1910 |
Takes a list of dictionaries and returns that list sorted in reverse order by |
| 1911 |
the key given in the argument. This works exactly the same as the above filter, |
| 1912 |
but the returned value will be in reverse order. |
| 1913 |
|
| 1914 |
.. templatefilter:: divisibleby |
| 1915 |
|
| 1916 |
``divisibleby`` |
| 1917 |
--------------- |
| 1918 |
|
| 1919 |
Returns ``True`` if the value is divisible by the argument. |
| 1920 |
|
| 1921 |
For example: |
| 1922 |
|
| 1923 |
.. code-block:: html+django |
| 1924 |
|
| 1925 |
{{ value|divisibleby:"3" }} |
| 1926 |
|
| 1927 |
If ``value`` is ``21``, the output would be ``True``. |
| 1928 |
|
| 1929 |
.. templatefilter:: escape |
| 1930 |
|
| 1931 |
``escape`` |
| 1932 |
---------- |
| 1933 |
|
| 1934 |
Escapes a string's HTML. Specifically, it makes these replacements: |
| 1935 |
|
| 1936 |
* ``<`` is converted to ``<`` |
| 1937 |
* ``>`` is converted to ``>`` |
| 1938 |
* ``'`` (single quote) is converted to ``'`` |
| 1939 |
* ``"`` (double quote) is converted to ``"`` |
| 1940 |
* ``&`` is converted to ``&`` |
| 1941 |
|
| 1942 |
Applying ``escape`` to a variable that would normally have auto-escaping |
| 1943 |
applied to the result will only result in one round of escaping being done. So |
| 1944 |
it is safe to use this function even in auto-escaping environments. If you want |
| 1945 |
multiple escaping passes to be applied, use the :tfilter:`force_escape` filter. |
| 1946 |
|
| 1947 |
For example, you can apply ``escape`` to fields when :ttag:`autoescape` is off: |
| 1948 |
|
| 1949 |
.. code-block:: html+django |
| 1950 |
|
| 1951 |
{% autoescape off %} |
| 1952 |
{{ title|escape }} |
| 1953 |
{% endautoescape %} |
| 1954 |
|
| 1955 |
.. admonition:: Chaining ``escape`` with other filters |
| 1956 |
|
| 1957 |
As mentioned in the :ttag:`autoescape` section, when filters including |
| 1958 |
``escape`` are chained together, it can result in unexpected outcomes if |
| 1959 |
preceding filters mark a potentially unsafe string as safe due to the lack |
| 1960 |
of escaping caused by :ttag:`autoescape` being ``off``. |
| 1961 |
|
| 1962 |
In such cases, chaining ``escape`` would not reescape strings that have |
| 1963 |
already been marked as safe. |
| 1964 |
|
| 1965 |
This is especially important when using filters that operate on sequences, |
| 1966 |
for example :tfilter:`join`. If you need to escape each element in a |
| 1967 |
sequence, use the dedicated :tfilter:`escapeseq` filter. |
| 1968 |
|
| 1969 |
.. templatefilter:: escapejs |
| 1970 |
|
| 1971 |
``escapejs`` |
| 1972 |
------------ |
| 1973 |
|
| 1974 |
Escapes characters for use as a whole JavaScript string literal, within single |
| 1975 |
or double quotes, as below. This filter does not make the string safe for use |
| 1976 |
in *"JavaScript template literals"* (the JavaScript backtick syntax). Any other |
| 1977 |
uses not listed above are not supported. It is generally recommended that data |
| 1978 |
should be passed using HTML ``data-`` attributes, or the :tfilter:`json_script` |
| 1979 |
filter, rather than in embedded JavaScript. |
| 1980 |
|
| 1981 |
For example: |
| 1982 |
|
| 1983 |
.. code-block:: html+django |
| 1984 |
|
| 1985 |
<script> |
| 1986 |
let myValue = '{{ value|escapejs }}' |
| 1987 |
|
| 1988 |
.. templatefilter:: escapeseq |
| 1989 |
|
| 1990 |
``escapeseq`` |
| 1991 |
------------- |
| 1992 |
|
| 1993 |
Applies the :tfilter:`escape` filter to each element of a sequence. Useful in |
| 1994 |
conjunction with other filters that operate on sequences, such as |
| 1995 |
:tfilter:`join`. For example: |
| 1996 |
|
| 1997 |
.. code-block:: html+django |
| 1998 |
|
| 1999 |
{% autoescape off %} |
| 2000 |
{{ my_list|escapeseq|join:", " }} |
| 2001 |
{% endautoescape %} |
| 2002 |
|
| 2003 |
.. templatefilter:: filesizeformat |
| 2004 |
|
| 2005 |
``filesizeformat`` |
| 2006 |
------------------ |
| 2007 |
|
| 2008 |
Formats the value like a 'human-readable' file size (i.e. ``'13 KB'``, |
| 2009 |
``'4.1 MB'``, ``'102 bytes'``, etc.). |
| 2010 |
|
| 2011 |
For example: |
| 2012 |
|
| 2013 |
.. code-block:: html+django |
| 2014 |
|
| 2015 |
{{ value|filesizeformat }} |
| 2016 |
|
| 2017 |
If ``value`` is 123456789, the output would be ``117.7 MB``. |
| 2018 |
|
| 2019 |
.. admonition:: File sizes and SI units |
| 2020 |
|
| 2021 |
Strictly speaking, ``filesizeformat`` does not conform to the International |
| 2022 |
System of Units which recommends using KiB, MiB, GiB, etc. when byte sizes |
| 2023 |
are calculated in powers of 1024 (which is the case here). Instead, Django |
| 2024 |
uses traditional unit names (KB, MB, GB, etc.) corresponding to names that |
| 2025 |
are more commonly used. |
| 2026 |
|
| 2027 |
.. templatefilter:: first |
| 2028 |
|
| 2029 |
``first`` |
| 2030 |
--------- |
| 2031 |
|
| 2032 |
Returns the first item in a list. |
| 2033 |
|
| 2034 |
For example: |
| 2035 |
|
| 2036 |
.. code-block:: html+django |
| 2037 |
|
| 2038 |
{{ value|first }} |
| 2039 |
|
| 2040 |
If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``. |
| 2041 |
|
| 2042 |
.. templatefilter:: floatformat |
| 2043 |
|
| 2044 |
``floatformat`` |
| 2045 |
--------------- |
| 2046 |
|
| 2047 |
When used without an argument, rounds a floating-point number to one decimal |
| 2048 |
place -- but only if there's a decimal part to be displayed. For example: |
| 2049 |
|
| 2050 |
============ =========================== ======== |
| 2051 |
``value`` Template Output |
| 2052 |
============ =========================== ======== |
| 2053 |
``34.23234`` ``{{ value|floatformat }}`` ``34.2`` |
| 2054 |
``34.00000`` ``{{ value|floatformat }}`` ``34`` |
| 2055 |
``34.26000`` ``{{ value|floatformat }}`` ``34.3`` |
| 2056 |
============ =========================== ======== |
| 2057 |
|
| 2058 |
If used with a numeric integer argument, ``floatformat`` rounds a number to |
| 2059 |
that many decimal places. For example: |
| 2060 |
|
| 2061 |
============ ============================= ========== |
| 2062 |
``value`` Template Output |
| 2063 |
============ ============================= ========== |
| 2064 |
``34.23234`` ``{{ value|floatformat:3 }}`` ``34.232`` |
| 2065 |
``34.00000`` ``{{ value|floatformat:3 }}`` ``34.000`` |
| 2066 |
``34.26000`` ``{{ value|floatformat:3 }}`` ``34.260`` |
| 2067 |
============ ============================= ========== |
| 2068 |
|
| 2069 |
Particularly useful is passing 0 (zero) as the argument which will round the |
| 2070 |
float to the nearest integer. |
| 2071 |
|
| 2072 |
============ ================================ ========== |
| 2073 |
``value`` Template Output |
| 2074 |
============ ================================ ========== |
| 2075 |
``34.23234`` ``{{ value|floatformat:"0" }}`` ``34`` |
| 2076 |
``34.00000`` ``{{ value|floatformat:"0" }}`` ``34`` |
| 2077 |
``39.56000`` ``{{ value|floatformat:"0" }}`` ``40`` |
| 2078 |
============ ================================ ========== |
| 2079 |
|
| 2080 |
If the argument passed to ``floatformat`` is negative, it will round a number |
| 2081 |
to that many decimal places -- but only if there's a decimal part to be |
| 2082 |
displayed. For example: |
| 2083 |
|
| 2084 |
============ ================================ ========== |
| 2085 |
``value`` Template Output |
| 2086 |
============ ================================ ========== |
| 2087 |
``34.23234`` ``{{ value|floatformat:"-3" }}`` ``34.232`` |
| 2088 |
``34.00000`` ``{{ value|floatformat:"-3" }}`` ``34`` |
| 2089 |
``34.26000`` ``{{ value|floatformat:"-3" }}`` ``34.260`` |
| 2090 |
============ ================================ ========== |
| 2091 |
|
| 2092 |
If the argument passed to ``floatformat`` has the ``g`` suffix, it will force |
| 2093 |
grouping by the :setting:`THOUSAND_SEPARATOR` for the active locale. For |
| 2094 |
example, when the active locale is ``en`` (English): |
| 2095 |
|
| 2096 |
============ ================================= ============= |
| 2097 |
``value`` Template Output |
| 2098 |
============ ================================= ============= |
| 2099 |
``34232.34`` ``{{ value|floatformat:"2g" }}`` ``34,232.34`` |
| 2100 |
``34232.06`` ``{{ value|floatformat:"g" }}`` ``34,232.1`` |
| 2101 |
``34232.00`` ``{{ value|floatformat:"-3g" }}`` ``34,232`` |
| 2102 |
============ ================================= ============= |
| 2103 |
|
| 2104 |
Output is always localized (independently of the :ttag:`{% localize off %} |
| 2105 |
<localize>` tag) unless the argument passed to ``floatformat`` has the ``u`` |
| 2106 |
suffix, which will force disabling localization. For example, when the active |
| 2107 |
locale is ``pl`` (Polish): |
| 2108 |
|
| 2109 |
============ ================================= ============= |
| 2110 |
``value`` Template Output |
| 2111 |
============ ================================= ============= |
| 2112 |
``34.23234`` ``{{ value|floatformat:"3" }}`` ``34,232`` |
| 2113 |
``34.23234`` ``{{ value|floatformat:"3u" }}`` ``34.232`` |
| 2114 |
============ ================================= ============= |
| 2115 |
|
| 2116 |
Using ``floatformat`` with no argument is equivalent to using ``floatformat`` |
| 2117 |
with an argument of ``-1``. |
| 2118 |
|
| 2119 |
.. templatefilter:: force_escape |
| 2120 |
|
| 2121 |
``force_escape`` |
| 2122 |
---------------- |
| 2123 |
|
| 2124 |
Applies HTML escaping to a string (see the :tfilter:`escape` filter for |
| 2125 |
details). This filter is applied *immediately* and returns a new, escaped |
| 2126 |
string. This is useful in the rare cases where you need multiple escaping or |
| 2127 |
want to apply other filters to the escaped results. Normally, you want to use |
| 2128 |
the :tfilter:`escape` filter. |
| 2129 |
|
| 2130 |
For example, if you want to catch the ``<p>`` HTML elements created by |
| 2131 |
the :tfilter:`linebreaks` filter: |
| 2132 |
|
| 2133 |
.. code-block:: html+django |
| 2134 |
|
| 2135 |
{% autoescape off %} |
| 2136 |
{{ body|linebreaks|force_escape }} |
| 2137 |
{% endautoescape %} |
| 2138 |
|
| 2139 |
.. templatefilter:: get_digit |
| 2140 |
|
| 2141 |
``get_digit`` |
| 2142 |
------------- |
| 2143 |
|
| 2144 |
Given a whole number, returns the requested digit, where 1 is the right-most |
| 2145 |
digit, 2 is the second-right-most digit, etc. Returns the original value for |
| 2146 |
invalid input (if input or argument is not an integer, or if argument is less |
| 2147 |
than 1). Otherwise, output is always an integer. |
| 2148 |
|
| 2149 |
For example: |
| 2150 |
|
| 2151 |
.. code-block:: html+django |
| 2152 |
|
| 2153 |
{{ value|get_digit:"2" }} |
| 2154 |
|
| 2155 |
If ``value`` is ``123456789``, the output will be ``8``. |
| 2156 |
|
| 2157 |
.. templatefilter:: iriencode |
| 2158 |
|
| 2159 |
``iriencode`` |
| 2160 |
------------- |
| 2161 |
|
| 2162 |
Converts an IRI (Internationalized Resource Identifier) to a string that is |
| 2163 |
suitable for including in a URL. This is necessary if you're trying to use |
| 2164 |
strings containing non-ASCII characters in a URL. |
| 2165 |
|
| 2166 |
It's safe to use this filter on a string that has already gone through the |
| 2167 |
:tfilter:`urlencode` filter. |
| 2168 |
|
| 2169 |
For example: |
| 2170 |
|
| 2171 |
.. code-block:: html+django |
| 2172 |
|
| 2173 |
{{ value|iriencode }} |
| 2174 |
|
| 2175 |
If ``value`` is ``"?test=I ♥ Django"``, the output will be |
| 2176 |
``"?test=I%20%E2%99%A5%20Django"``. |
| 2177 |
|
| 2178 |
.. templatefilter:: join |
| 2179 |
|
| 2180 |
``join`` |
| 2181 |
-------- |
| 2182 |
|
| 2183 |
Joins a list with a string, like Python's ``str.join(list)`` |
| 2184 |
|
| 2185 |
For example: |
| 2186 |
|
| 2187 |
.. code-block:: html+django |
| 2188 |
|
| 2189 |
{{ value|join:" // " }} |
| 2190 |
|
| 2191 |
If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string |
| 2192 |
``"a // b // c"``. |
| 2193 |
|
| 2194 |
.. templatefilter:: json_script |
| 2195 |
|
| 2196 |
``json_script`` |
| 2197 |
--------------- |
| 2198 |
|
| 2199 |
Safely outputs a Python object as JSON, wrapped in a ``<script>`` tag, ready |
| 2200 |
for use with JavaScript. |
| 2201 |
|
| 2202 |
**Argument:** The optional HTML "id" of the ``<script>`` tag. |
| 2203 |
|
| 2204 |
For example: |
| 2205 |
|
| 2206 |
.. code-block:: html+django |
| 2207 |
|
| 2208 |
{{ value|json_script:"hello-data" }} |
| 2209 |
|
| 2210 |
If ``value`` is the dictionary ``{'hello': 'world'}``, the output will be: |
| 2211 |
|
| 2212 |
.. code-block:: html |
| 2213 |
|
| 2214 |
<script id="hello-data" type="application/json">{"hello": "world"}</script> |
| 2215 |
|
| 2216 |
The resulting data can be accessed in JavaScript like this: |
| 2217 |
|
| 2218 |
.. code-block:: javascript |
| 2219 |
|
| 2220 |
const value = JSON.parse(document.getElementById('hello-data').textContent); |
| 2221 |
|
| 2222 |
XSS attacks are mitigated by escaping the characters "<", ">" and "&". For |
| 2223 |
example if ``value`` is ``{'hello': 'world</script>&'}``, the output is: |
| 2224 |
|
| 2225 |
.. code-block:: html |
| 2226 |
|
| 2227 |
<script id="hello-data" type="application/json">{"hello": "world\\u003C/script\\u003E\\u0026amp;"}</script> |
| 2228 |
|
| 2229 |
This is compatible with a strict Content Security Policy that prohibits in-page |
| 2230 |
script execution. It also maintains a clean separation between passive data and |
| 2231 |
executable code. |
| 2232 |
|
| 2233 |
.. templatefilter:: last |
| 2234 |
|
| 2235 |
``last`` |
| 2236 |
-------- |
| 2237 |
|
| 2238 |
Returns the last item in a list. |
| 2239 |
|
| 2240 |
For example: |
| 2241 |
|
| 2242 |
.. code-block:: html+django |
| 2243 |
|
| 2244 |
{{ value|last }} |
| 2245 |
|
| 2246 |
If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the |
| 2247 |
string ``"d"``. |
| 2248 |
|
| 2249 |
.. templatefilter:: length |
| 2250 |
|
| 2251 |
``length`` |
| 2252 |
---------- |
| 2253 |
|
| 2254 |
Returns the length of the value. This works for both strings and lists. |
| 2255 |
|
| 2256 |
For example: |
| 2257 |
|
| 2258 |
.. code-block:: html+django |
| 2259 |
|
| 2260 |
{{ value|length }} |
| 2261 |
|
| 2262 |
If ``value`` is ``['a', 'b', 'c', 'd']`` or ``"abcd"``, the output will be |
| 2263 |
``4``. |
| 2264 |
|
| 2265 |
The filter returns ``0`` for an undefined variable. |
| 2266 |
|
| 2267 |
.. templatefilter:: linebreaks |
| 2268 |
|
| 2269 |
``linebreaks`` |
| 2270 |
-------------- |
| 2271 |
|
| 2272 |
Replaces line breaks in plain text with appropriate HTML; a single |
| 2273 |
newline becomes an HTML line break (``<br>``) and a new line |
| 2274 |
followed by a blank line becomes a paragraph break (``</p>``). |
| 2275 |
|
| 2276 |
For example: |
| 2277 |
|
| 2278 |
.. code-block:: html+django |
| 2279 |
|
| 2280 |
{{ value|linebreaks }} |
| 2281 |
|
| 2282 |
If ``value`` is ``Joel\nis a slug``, the output will be ``<p>Joel<br>is a |
| 2283 |
slug</p>``. |
| 2284 |
|
| 2285 |
.. templatefilter:: linebreaksbr |
| 2286 |
|
| 2287 |
``linebreaksbr`` |
| 2288 |
---------------- |
| 2289 |
|
| 2290 |
Converts all newlines in a piece of plain text to HTML line breaks |
| 2291 |
(``<br>``). |
| 2292 |
|
| 2293 |
For example: |
| 2294 |
|
| 2295 |
.. code-block:: html+django |
| 2296 |
|
| 2297 |
{{ value|linebreaksbr }} |
| 2298 |
|
| 2299 |
If ``value`` is ``Joel\nis a slug``, the output will be ``Joel<br>is a |
| 2300 |
slug``. |
| 2301 |
|
| 2302 |
.. templatefilter:: linenumbers |
| 2303 |
|
| 2304 |
``linenumbers`` |
| 2305 |
--------------- |
| 2306 |
|
| 2307 |
Displays text with line numbers. |
| 2308 |
|
| 2309 |
For example: |
| 2310 |
|
| 2311 |
.. code-block:: html+django |
| 2312 |
|
| 2313 |
{{ value|linenumbers }} |
| 2314 |
|
| 2315 |
If ``value`` is: |
| 2316 |
|
| 2317 |
.. code-block:: html+django |
| 2318 |
|
| 2319 |
one |
| 2320 |
two |
| 2321 |
three |
| 2322 |
|
| 2323 |
the output will be: |
| 2324 |
|
| 2325 |
.. code-block:: html+django |
| 2326 |
|
| 2327 |
1. one |
| 2328 |
2. two |
| 2329 |
3. three |
| 2330 |
|
| 2331 |
.. templatefilter:: ljust |
| 2332 |
|
| 2333 |
``ljust`` |
| 2334 |
--------- |
| 2335 |
|
| 2336 |
Left-aligns the value in a field of a given width. |
| 2337 |
|
| 2338 |
**Argument:** field size |
| 2339 |
|
| 2340 |
For example: |
| 2341 |
|
| 2342 |
.. code-block:: html+django |
| 2343 |
|
| 2344 |
"{{ value|ljust:"10" }}" |
| 2345 |
|
| 2346 |
If ``value`` is ``Django``, the output will be ``"Django "``. |
| 2347 |
|
| 2348 |
.. templatefilter:: lower |
| 2349 |
|
| 2350 |
``lower`` |
| 2351 |
--------- |
| 2352 |
|
| 2353 |
Converts a string into all lowercase. |
| 2354 |
|
| 2355 |
For example: |
| 2356 |
|
| 2357 |
.. code-block:: html+django |
| 2358 |
|
| 2359 |
{{ value|lower }} |
| 2360 |
|
| 2361 |
If ``value`` is ``Totally LOVING this Album!``, the output will be |
| 2362 |
``totally loving this album!``. |
| 2363 |
|
| 2364 |
.. templatefilter:: make_list |
| 2365 |
|
| 2366 |
``make_list`` |
| 2367 |
------------- |
| 2368 |
|
| 2369 |
Returns the value turned into a list. For a string, it's a list of characters. |
| 2370 |
For an integer, the argument is cast to a string before creating a list. |
| 2371 |
|
| 2372 |
For example: |
| 2373 |
|
| 2374 |
.. code-block:: html+django |
| 2375 |
|
| 2376 |
{{ value|make_list }} |
| 2377 |
|
| 2378 |
If ``value`` is the string ``"Joel"``, the output would be the list |
| 2379 |
``['J', 'o', 'e', 'l']``. If ``value`` is ``123``, the output will be the |
| 2380 |
list ``['1', '2', '3']``. |
| 2381 |
|
| 2382 |
.. templatefilter:: phone2numeric |
| 2383 |
|
| 2384 |
``phone2numeric`` |
| 2385 |
----------------- |
| 2386 |
|
| 2387 |
Converts a phone number (possibly containing letters) to its numerical |
| 2388 |
equivalent. |
| 2389 |
|
| 2390 |
The input doesn't have to be a valid phone number. This will happily convert |
| 2391 |
any string. |
| 2392 |
|
| 2393 |
For example: |
| 2394 |
|
| 2395 |
.. code-block:: html+django |
| 2396 |
|
| 2397 |
{{ value|phone2numeric }} |
| 2398 |
|
| 2399 |
If ``value`` is ``800-COLLECT``, the output will be ``800-2655328``. |
| 2400 |
|
| 2401 |
.. templatefilter:: pluralize |
| 2402 |
|
| 2403 |
``pluralize`` |
| 2404 |
------------- |
| 2405 |
|
| 2406 |
Returns a plural suffix if the value is not ``1``, ``'1'``, or an object of |
| 2407 |
length 1. By default, this suffix is ``'s'``. |
| 2408 |
|
| 2409 |
Example: |
| 2410 |
|
| 2411 |
.. code-block:: html+django |
| 2412 |
|
| 2413 |
You have {{ num_messages }} message{{ num_messages|pluralize }}. |
| 2414 |
|
| 2415 |
If ``num_messages`` is ``1``, the output will be ``You have 1 message.`` |
| 2416 |
If ``num_messages`` is ``2`` the output will be ``You have 2 messages.`` |
| 2417 |
|
| 2418 |
For words that require a suffix other than ``'s'``, you can provide an alternate |
| 2419 |
suffix as a parameter to the filter. |
| 2420 |
|
| 2421 |
Example: |
| 2422 |
|
| 2423 |
.. code-block:: html+django |
| 2424 |
|
| 2425 |
You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}. |
| 2426 |
|
| 2427 |
For words that don't pluralize by simple suffix, you can specify both a |
| 2428 |
singular and plural suffix, separated by a comma. |
| 2429 |
|
| 2430 |
Example: |
| 2431 |
|
| 2432 |
.. code-block:: html+django |
| 2433 |
|
| 2434 |
You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}. |
| 2435 |
|
| 2436 |
.. note:: Use :ttag:`blocktranslate` to pluralize translated strings. |
| 2437 |
|
| 2438 |
.. templatefilter:: pprint |
| 2439 |
|
| 2440 |
``pprint`` |
| 2441 |
---------- |
| 2442 |
|
| 2443 |
A wrapper around :func:`pprint.pprint` -- for debugging, really. |
| 2444 |
|
| 2445 |
.. templatefilter:: random |
| 2446 |
|
| 2447 |
``random`` |
| 2448 |
---------- |
| 2449 |
|
| 2450 |
Returns a random item from the given list. |
| 2451 |
|
| 2452 |
For example: |
| 2453 |
|
| 2454 |
.. code-block:: html+django |
| 2455 |
|
| 2456 |
{{ value|random }} |
| 2457 |
|
| 2458 |
If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``. |
| 2459 |
|
| 2460 |
.. templatefilter:: rjust |
| 2461 |
|
| 2462 |
``rjust`` |
| 2463 |
--------- |
| 2464 |
|
| 2465 |
Right-aligns the value in a field of a given width. |
| 2466 |
|
| 2467 |
**Argument:** field size |
| 2468 |
|
| 2469 |
For example: |
| 2470 |
|
| 2471 |
.. code-block:: html+django |
| 2472 |
|
| 2473 |
"{{ value|rjust:"10" }}" |
| 2474 |
|
| 2475 |
If ``value`` is ``Django``, the output will be ``" Django"``. |
| 2476 |
|
| 2477 |
.. templatefilter:: safe |
| 2478 |
|
| 2479 |
``safe`` |
| 2480 |
-------- |
| 2481 |
|
| 2482 |
Marks a string as not requiring further HTML escaping prior to output. When |
| 2483 |
autoescaping is off, this filter has no effect. |
| 2484 |
|
| 2485 |
.. note:: |
| 2486 |
|
| 2487 |
If you are chaining filters, a filter applied after ``safe`` can |
| 2488 |
make the contents unsafe again. For example, the following code |
| 2489 |
prints the variable as is, unescaped: |
| 2490 |
|
| 2491 |
.. code-block:: html+django |
| 2492 |
|
| 2493 |
{{ var|safe|escape }} |
| 2494 |
|
| 2495 |
.. templatefilter:: safeseq |
| 2496 |
|
| 2497 |
``safeseq`` |
| 2498 |
----------- |
| 2499 |
|
| 2500 |
Applies the :tfilter:`safe` filter to each element of a sequence. Useful in |
| 2501 |
conjunction with other filters that operate on sequences, such as |
| 2502 |
:tfilter:`join`. For example: |
| 2503 |
|
| 2504 |
.. code-block:: html+django |
| 2505 |
|
| 2506 |
{{ some_list|safeseq|join:", " }} |
| 2507 |
|
| 2508 |
You couldn't use the :tfilter:`safe` filter directly in this case, as it would |
| 2509 |
first convert the variable into a string, rather than working with the |
| 2510 |
individual elements of the sequence. |
| 2511 |
|
| 2512 |
.. templatefilter:: slice |
| 2513 |
|
| 2514 |
``slice`` |
| 2515 |
--------- |
| 2516 |
|
| 2517 |
Returns a slice of the list. |
| 2518 |
|
| 2519 |
Uses the same syntax as Python's list slicing. See the `Python documentation |
| 2520 |
<https://docs.python.org/3/tutorial/introduction.html#lists>`_ for an |
| 2521 |
introduction. |
| 2522 |
|
| 2523 |
Example: |
| 2524 |
|
| 2525 |
.. code-block:: html+django |
| 2526 |
|
| 2527 |
{{ some_list|slice:":2" }} |
| 2528 |
|
| 2529 |
If ``some_list`` is ``['a', 'b', 'c']``, the output will be ``['a', 'b']``. |
| 2530 |
|
| 2531 |
.. templatefilter:: slugify |
| 2532 |
|
| 2533 |
``slugify`` |
| 2534 |
----------- |
| 2535 |
|
| 2536 |
Converts to ASCII. Converts spaces to hyphens. Removes characters that aren't |
| 2537 |
alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips |
| 2538 |
leading and trailing whitespace. |
| 2539 |
|
| 2540 |
For example: |
| 2541 |
|
| 2542 |
.. code-block:: html+django |
| 2543 |
|
| 2544 |
{{ value|slugify }} |
| 2545 |
|
| 2546 |
If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``. |
| 2547 |
|
| 2548 |
.. templatefilter:: stringformat |
| 2549 |
|
| 2550 |
``stringformat`` |
| 2551 |
---------------- |
| 2552 |
|
| 2553 |
Formats the variable according to the argument, a string formatting specifier. |
| 2554 |
This specifier uses the :ref:`old-string-formatting` syntax, with the exception |
| 2555 |
that the leading "%" is dropped. |
| 2556 |
|
| 2557 |
For example: |
| 2558 |
|
| 2559 |
.. code-block:: html+django |
| 2560 |
|
| 2561 |
{{ value|stringformat:"E" }} |
| 2562 |
|
| 2563 |
If ``value`` is ``10``, the output will be ``1.000000E+01``. |
| 2564 |
|
| 2565 |
.. templatefilter:: striptags |
| 2566 |
|
| 2567 |
``striptags`` |
| 2568 |
------------- |
| 2569 |
|
| 2570 |
Makes all possible efforts to strip all [X]HTML tags. |
| 2571 |
|
| 2572 |
For example: |
| 2573 |
|
| 2574 |
.. code-block:: html+django |
| 2575 |
|
| 2576 |
{{ value|striptags }} |
| 2577 |
|
| 2578 |
If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``, the |
| 2579 |
output will be ``"Joel is a slug"``. |
| 2580 |
|
| 2581 |
.. admonition:: No safety guarantee |
| 2582 |
|
| 2583 |
Note that ``striptags`` doesn't give any guarantee about its output being |
| 2584 |
HTML safe, particularly with non valid HTML input. So **NEVER** apply the |
| 2585 |
``safe`` filter to a ``striptags`` output. If you are looking for something |
| 2586 |
more robust, consider using a third-party HTML sanitizing tool. |
| 2587 |
|
| 2588 |
.. templatefilter:: time |
| 2589 |
|
| 2590 |
``time`` |
| 2591 |
-------- |
| 2592 |
|
| 2593 |
Formats a time according to the given format. |
| 2594 |
|
| 2595 |
Given format can be the predefined one :setting:`TIME_FORMAT`, or a custom |
| 2596 |
format, same as the :tfilter:`date` filter. Note that the predefined format |
| 2597 |
is locale-dependent. |
| 2598 |
|
| 2599 |
For example: |
| 2600 |
|
| 2601 |
.. code-block:: html+django |
| 2602 |
|
| 2603 |
{{ value|time:"H:i" }} |
| 2604 |
|
| 2605 |
If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be |
| 2606 |
the string ``"01:23"``. |
| 2607 |
|
| 2608 |
Note that you can backslash-escape a format string if you want to use the |
| 2609 |
"raw" value. In this example, both "h" and "m" are backslash-escaped, because |
| 2610 |
otherwise each is a format string that displays the hour and the month, |
| 2611 |
respectively: |
| 2612 |
|
| 2613 |
.. code-block:: html+django |
| 2614 |
|
| 2615 |
{{ value|time:"H\h i\m" }} |
| 2616 |
|
| 2617 |
This would display as "01h 23m". |
| 2618 |
|
| 2619 |
Another example: |
| 2620 |
|
| 2621 |
Assuming that :setting:`LANGUAGE_CODE` is, for example, ``"de"``, then for: |
| 2622 |
|
| 2623 |
.. code-block:: html+django |
| 2624 |
|
| 2625 |
{{ value|time:"TIME_FORMAT" }} |
| 2626 |
|
| 2627 |
the output will be the string ``"01:23"`` (The ``"TIME_FORMAT"`` format |
| 2628 |
specifier for the ``de`` locale as shipped with Django is ``"H:i"``). |
| 2629 |
|
| 2630 |
The ``time`` filter will only accept parameters in the format string that |
| 2631 |
relate to the time of day, not the date. If you need to format a ``date`` |
| 2632 |
value, use the :tfilter:`date` filter instead (or along with :tfilter:`time` if |
| 2633 |
you need to render a full :py:class:`~datetime.datetime` value). |
| 2634 |
|
| 2635 |
There is one exception the above rule: When passed a ``datetime`` value with |
| 2636 |
attached timezone information (a :ref:`time-zone-aware |
| 2637 |
<naive_vs_aware_datetimes>` ``datetime`` instance) the ``time`` filter will |
| 2638 |
accept the timezone-related :ref:`format specifiers |
| 2639 |
<date-and-time-formatting-specifiers>` ``'e'``, ``'O'`` , ``'T'`` and ``'Z'``. |
| 2640 |
|
| 2641 |
When used without a format string, the ``TIME_FORMAT`` format specifier is |
| 2642 |
used: |
| 2643 |
|
| 2644 |
.. code-block:: html+django |
| 2645 |
|
| 2646 |
{{ value|time }} |
| 2647 |
|
| 2648 |
is the same as: |
| 2649 |
|
| 2650 |
.. code-block:: html+django |
| 2651 |
|
| 2652 |
{{ value|time:"TIME_FORMAT" }} |
| 2653 |
|
| 2654 |
.. templatefilter:: timesince |
| 2655 |
|
| 2656 |
``timesince`` |
| 2657 |
------------- |
| 2658 |
|
| 2659 |
Formats a date as the time since that date (e.g., "4 days, 6 hours"). |
| 2660 |
|
| 2661 |
Takes an optional argument that is a variable containing the date to use as |
| 2662 |
the comparison point (without the argument, the comparison point is *now*). |
| 2663 |
For example, if ``blog_date`` is a date instance representing midnight on 1 |
| 2664 |
June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006, |
| 2665 |
then the following would return "8 hours": |
| 2666 |
|
| 2667 |
.. code-block:: html+django |
| 2668 |
|
| 2669 |
{{ blog_date|timesince:comment_date }} |
| 2670 |
|
| 2671 |
Comparing offset-naive and offset-aware datetimes will return an empty string. |
| 2672 |
|
| 2673 |
Minutes is the smallest unit used, and "0 minutes" will be returned for any |
| 2674 |
date that is in the future relative to the comparison point. |
| 2675 |
|
| 2676 |
.. templatefilter:: timeuntil |
| 2677 |
|
| 2678 |
``timeuntil`` |
| 2679 |
------------- |
| 2680 |
|
| 2681 |
Similar to ``timesince``, except that it measures the time from now until the |
| 2682 |
given date or datetime. For example, if today is 1 June 2006 and |
| 2683 |
``conference_date`` is a date instance holding 29 June 2006, then |
| 2684 |
``{{ conference_date|timeuntil }}`` will return "4 weeks". |
| 2685 |
|
| 2686 |
Takes an optional argument that is a variable containing the date to use as |
| 2687 |
the comparison point (instead of *now*). If ``from_date`` contains 22 June |
| 2688 |
2006, then the following will return "1 week": |
| 2689 |
|
| 2690 |
.. code-block:: html+django |
| 2691 |
|
| 2692 |
{{ conference_date|timeuntil:from_date }} |
| 2693 |
|
| 2694 |
Comparing offset-naive and offset-aware datetimes will return an empty string. |
| 2695 |
|
| 2696 |
Minutes is the smallest unit used, and "0 minutes" will be returned for any |
| 2697 |
date that is in the past relative to the comparison point. |
| 2698 |
|
| 2699 |
.. templatefilter:: title |
| 2700 |
|
| 2701 |
``title`` |
| 2702 |
--------- |
| 2703 |
|
| 2704 |
Converts a string into titlecase by making words start with an uppercase |
| 2705 |
character and the remaining characters lowercase. This tag makes no effort to |
| 2706 |
keep "trivial words" in lowercase. |
| 2707 |
|
| 2708 |
For example: |
| 2709 |
|
| 2710 |
.. code-block:: html+django |
| 2711 |
|
| 2712 |
{{ value|title }} |
| 2713 |
|
| 2714 |
If ``value`` is ``"my FIRST post"``, the output will be ``"My First Post"``. |
| 2715 |
|
| 2716 |
.. templatefilter:: truncatechars |
| 2717 |
|
| 2718 |
``truncatechars`` |
| 2719 |
----------------- |
| 2720 |
|
| 2721 |
Truncates a string if it is longer than the specified number of characters. |
| 2722 |
Truncated strings will end with a translatable ellipsis character ("…"). |
| 2723 |
|
| 2724 |
**Argument:** Number of characters to truncate to |
| 2725 |
|
| 2726 |
For example: |
| 2727 |
|
| 2728 |
.. code-block:: html+django |
| 2729 |
|
| 2730 |
{{ value|truncatechars:7 }} |
| 2731 |
|
| 2732 |
If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel i…"``. |
| 2733 |
|
| 2734 |
.. templatefilter:: truncatechars_html |
| 2735 |
|
| 2736 |
``truncatechars_html`` |
| 2737 |
---------------------- |
| 2738 |
|
| 2739 |
Similar to :tfilter:`truncatechars`, except that it is aware of HTML tags. Any |
| 2740 |
tags that are opened in the string and not closed before the truncation point |
| 2741 |
are closed immediately after the truncation. |
| 2742 |
|
| 2743 |
For example: |
| 2744 |
|
| 2745 |
.. code-block:: html+django |
| 2746 |
|
| 2747 |
{{ value|truncatechars_html:7 }} |
| 2748 |
|
| 2749 |
If ``value`` is ``"<p>Joel is a slug</p>"``, the output will be |
| 2750 |
``"<p>Joel i…</p>"``. |
| 2751 |
|
| 2752 |
Newlines in the HTML content will be preserved. |
| 2753 |
|
| 2754 |
.. admonition:: Size of input string |
| 2755 |
|
| 2756 |
Processing large, potentially malformed HTML strings can be |
| 2757 |
resource-intensive and impact service performance. |
| 2758 |
|
| 2759 |
.. versionchanged:: 5.1 |
| 2760 |
|
| 2761 |
The input limit of five million characters was removed. |
| 2762 |
|
| 2763 |
.. templatefilter:: truncatewords |
| 2764 |
|
| 2765 |
``truncatewords`` |
| 2766 |
----------------- |
| 2767 |
|
| 2768 |
Truncates a string after a certain number of words. |
| 2769 |
|
| 2770 |
**Argument:** Number of words to truncate after |
| 2771 |
|
| 2772 |
For example: |
| 2773 |
|
| 2774 |
.. code-block:: html+django |
| 2775 |
|
| 2776 |
{{ value|truncatewords:2 }} |
| 2777 |
|
| 2778 |
If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is …"``. |
| 2779 |
|
| 2780 |
Newlines within the string will be removed. |
| 2781 |
|
| 2782 |
.. templatefilter:: truncatewords_html |
| 2783 |
|
| 2784 |
``truncatewords_html`` |
| 2785 |
---------------------- |
| 2786 |
|
| 2787 |
Similar to :tfilter:`truncatewords`, except that it is aware of HTML tags. Any |
| 2788 |
tags that are opened in the string and not closed before the truncation point, |
| 2789 |
are closed immediately after the truncation. |
| 2790 |
|
| 2791 |
This is less efficient than :tfilter:`truncatewords`, so should only be used |
| 2792 |
when it is being passed HTML text. |
| 2793 |
|
| 2794 |
For example: |
| 2795 |
|
| 2796 |
.. code-block:: html+django |
| 2797 |
|
| 2798 |
{{ value|truncatewords_html:2 }} |
| 2799 |
|
| 2800 |
If ``value`` is ``"<p>Joel is a slug</p>"``, the output will be |
| 2801 |
``"<p>Joel is …</p>"``. |
| 2802 |
|
| 2803 |
Newlines in the HTML content will be preserved. |
| 2804 |
|
| 2805 |
.. admonition:: Size of input string |
| 2806 |
|
| 2807 |
Processing large, potentially malformed HTML strings can be |
| 2808 |
resource-intensive and impact service performance. |
| 2809 |
|
| 2810 |
.. versionchanged:: 5.1 |
| 2811 |
|
| 2812 |
The input limit of five million characters was removed. |
| 2813 |
|
| 2814 |
.. templatefilter:: unordered_list |
| 2815 |
|
| 2816 |
``unordered_list`` |
| 2817 |
------------------ |
| 2818 |
|
| 2819 |
Recursively takes a self-nested list and returns an HTML unordered list -- |
| 2820 |
WITHOUT opening and closing ``<ul>`` tags. |
| 2821 |
|
| 2822 |
The list is assumed to be in the proper format. For example, if ``var`` |
| 2823 |
contains ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then |
| 2824 |
``{{ var|unordered_list }}`` would return: |
| 2825 |
|
| 2826 |
.. code-block:: html+django |
| 2827 |
|
| 2828 |
<li>States |
| 2829 |
<ul> |
| 2830 |
<li>Kansas |
| 2831 |
<ul> |
| 2832 |
<li>Lawrence</li> |
| 2833 |
<li>Topeka</li> |
| 2834 |
</ul> |
| 2835 |
</li> |
| 2836 |
<li>Illinois</li> |
| 2837 |
</ul> |
| 2838 |
</li> |
| 2839 |
|
| 2840 |
.. templatefilter:: upper |
| 2841 |
|
| 2842 |
``upper`` |
| 2843 |
--------- |
| 2844 |
|
| 2845 |
Converts a string into all uppercase. |
| 2846 |
|
| 2847 |
For example: |
| 2848 |
|
| 2849 |
.. code-block:: html+django |
| 2850 |
|
| 2851 |
{{ value|upper }} |
| 2852 |
|
| 2853 |
If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``. |
| 2854 |
|
| 2855 |
.. templatefilter:: urlencode |
| 2856 |
|
| 2857 |
``urlencode`` |
| 2858 |
------------- |
| 2859 |
|
| 2860 |
Escapes a value for use in a URL. |
| 2861 |
|
| 2862 |
For example: |
| 2863 |
|
| 2864 |
.. code-block:: html+django |
| 2865 |
|
| 2866 |
{{ value|urlencode }} |
| 2867 |
|
| 2868 |
If ``value`` is ``"https://www.example.org/foo?a=b&c=d"``, the output will be |
| 2869 |
``"https%3A//www.example.org/foo%3Fa%3Db%26c%3Dd"``. |
| 2870 |
|
| 2871 |
An optional argument containing the characters which should not be escaped can |
| 2872 |
be provided. |
| 2873 |
|
| 2874 |
If not provided, the '/' character is assumed safe. An empty string can be |
| 2875 |
provided when *all* characters should be escaped. For example: |
| 2876 |
|
| 2877 |
.. code-block:: html+django |
| 2878 |
|
| 2879 |
{{ value|urlencode:"" }} |
| 2880 |
|
| 2881 |
If ``value`` is ``"https://www.example.org/"``, the output will be |
| 2882 |
``"https%3A%2F%2Fwww.example.org%2F"``. |
| 2883 |
|
| 2884 |
.. templatefilter:: urlize |
| 2885 |
|
| 2886 |
``urlize`` |
| 2887 |
---------- |
| 2888 |
|
| 2889 |
Converts URLs and email addresses in text into clickable links. |
| 2890 |
|
| 2891 |
This template tag works on links prefixed with ``http://``, ``https://``, or |
| 2892 |
``www.``. For example, ``https://djangocon.eu`` will get converted but |
| 2893 |
``djangocon.eu`` won't. |
| 2894 |
|
| 2895 |
It also supports domain-only links ending in one of the original top level |
| 2896 |
domains (``.com``, ``.edu``, ``.gov``, ``.int``, ``.mil``, ``.net``, and |
| 2897 |
``.org``). For example, ``djangoproject.com`` gets converted. |
| 2898 |
|
| 2899 |
Links can have trailing punctuation (periods, commas, close-parens) and leading |
| 2900 |
punctuation (opening parens), and ``urlize`` will still do the right thing. |
| 2901 |
|
| 2902 |
Links generated by ``urlize`` have a ``rel="nofollow"`` attribute added |
| 2903 |
to them. |
| 2904 |
|
| 2905 |
For example: |
| 2906 |
|
| 2907 |
.. code-block:: html+django |
| 2908 |
|
| 2909 |
{{ value|urlize }} |
| 2910 |
|
| 2911 |
If ``value`` is ``"Check out www.djangoproject.com"``, the output will be |
| 2912 |
``"Check out <a href="http://www.djangoproject.com" |
| 2913 |
rel="nofollow">www.djangoproject.com</a>"``. |
| 2914 |
|
| 2915 |
In addition to web links, ``urlize`` also converts email addresses into |
| 2916 |
``mailto:`` links. If ``value`` is |
| 2917 |
``"Send questions to [email protected]"``, the output will be |
| 2918 |
``"Send questions to <a href="mailto:[email protected]">[email protected]</a>"``. |
| 2919 |
|
| 2920 |
The ``urlize`` filter also takes an optional parameter ``autoescape``. If |
| 2921 |
``autoescape`` is ``True``, the link text and URLs will be escaped using |
| 2922 |
Django's built-in :tfilter:`escape` filter. The default value for |
| 2923 |
``autoescape`` is ``True``. |
| 2924 |
|
| 2925 |
.. note:: |
| 2926 |
|
| 2927 |
If ``urlize`` is applied to text that already contains HTML markup, or to |
| 2928 |
email addresses that contain single quotes (``'``), things won't work as |
| 2929 |
expected. Apply this filter only to plain text. |
| 2930 |
|
| 2931 |
.. templatefilter:: urlizetrunc |
| 2932 |
|
| 2933 |
``urlizetrunc`` |
| 2934 |
--------------- |
| 2935 |
|
| 2936 |
Converts URLs and email addresses into clickable links just like urlize_, but |
| 2937 |
truncates URLs longer than the given character limit. |
| 2938 |
|
| 2939 |
**Argument:** Number of characters that link text should be truncated to, |
| 2940 |
including the ellipsis that's added if truncation is necessary. |
| 2941 |
|
| 2942 |
For example: |
| 2943 |
|
| 2944 |
.. code-block:: html+django |
| 2945 |
|
| 2946 |
{{ value|urlizetrunc:15 }} |
| 2947 |
|
| 2948 |
If ``value`` is ``"Check out www.djangoproject.com"``, the output would be |
| 2949 |
``'Check out <a href="http://www.djangoproject.com" |
| 2950 |
rel="nofollow">www.djangoproj…</a>'``. |
| 2951 |
|
| 2952 |
As with urlize_, this filter should only be applied to plain text. |
| 2953 |
|
| 2954 |
.. templatefilter:: wordcount |
| 2955 |
|
| 2956 |
``wordcount`` |
| 2957 |
------------- |
| 2958 |
|
| 2959 |
Returns the number of words. |
| 2960 |
|
| 2961 |
For example: |
| 2962 |
|
| 2963 |
.. code-block:: html+django |
| 2964 |
|
| 2965 |
{{ value|wordcount }} |
| 2966 |
|
| 2967 |
If ``value`` is ``"Joel is a slug"``, the output will be ``4``. |
| 2968 |
|
| 2969 |
.. templatefilter:: wordwrap |
| 2970 |
|
| 2971 |
``wordwrap`` |
| 2972 |
------------ |
| 2973 |
|
| 2974 |
Wraps words at specified line length. |
| 2975 |
|
| 2976 |
**Argument:** number of characters at which to wrap the text |
| 2977 |
|
| 2978 |
For example: |
| 2979 |
|
| 2980 |
.. code-block:: html+django |
| 2981 |
|
| 2982 |
{{ value|wordwrap:5 }} |
| 2983 |
|
| 2984 |
If ``value`` is ``Joel is a slug``, the output would be: |
| 2985 |
|
| 2986 |
.. code-block:: html+django |
| 2987 |
|
| 2988 |
Joel |
| 2989 |
is a |
| 2990 |
slug |
| 2991 |
|
| 2992 |
.. templatefilter:: yesno |
| 2993 |
|
| 2994 |
``yesno`` |
| 2995 |
--------- |
| 2996 |
|
| 2997 |
Maps values for ``True``, ``False``, and (optionally) ``None``, to the strings |
| 2998 |
"yes", "no", "maybe", or a custom mapping passed as a comma-separated list, and |
| 2999 |
returns one of those strings according to the value: |
| 3000 |
|
| 3001 |
For example: |
| 3002 |
|
| 3003 |
.. code-block:: html+django |
| 3004 |
|
| 3005 |
{{ value|yesno:"yeah,no,maybe" }} |
| 3006 |
|
| 3007 |
========== ====================== =========================================== |
| 3008 |
Value Argument Outputs |
| 3009 |
========== ====================== =========================================== |
| 3010 |
``True`` ``yes`` |
| 3011 |
``True`` ``"yeah,no,maybe"`` ``yeah`` |
| 3012 |
``False`` ``"yeah,no,maybe"`` ``no`` |
| 3013 |
``None`` ``"yeah,no,maybe"`` ``maybe`` |
| 3014 |
``None`` ``"yeah,no"`` ``no`` (converts ``None`` to ``False`` |
| 3015 |
if no mapping for ``None`` is given) |
| 3016 |
========== ====================== =========================================== |
| 3017 |
|
| 3018 |
Internationalization tags and filters |
| 3019 |
===================================== |
| 3020 |
|
| 3021 |
Django provides template tags and filters to control each aspect of |
| 3022 |
:doc:`internationalization </topics/i18n/index>` in templates. They allow for |
| 3023 |
granular control of translations, formatting, and time zone conversions. |
| 3024 |
|
| 3025 |
``i18n`` |
| 3026 |
-------- |
| 3027 |
|
| 3028 |
This library allows specifying translatable text in templates. |
| 3029 |
To enable it, set :setting:`USE_I18N` to ``True``, then load it with |
| 3030 |
``{% load i18n %}``. |
| 3031 |
|
| 3032 |
See :ref:`specifying-translation-strings-in-template-code`. |
| 3033 |
|
| 3034 |
``l10n`` |
| 3035 |
-------- |
| 3036 |
|
| 3037 |
This library provides control over the localization of values in templates. |
| 3038 |
You only need to load the library using ``{% load l10n %}``. |
| 3039 |
|
| 3040 |
See :ref:`topic-l10n-templates`. |
| 3041 |
|
| 3042 |
``tz`` |
| 3043 |
------ |
| 3044 |
|
| 3045 |
This library provides control over time zone conversions in templates. |
| 3046 |
Like ``l10n``, you only need to load the library using ``{% load tz %}``, |
| 3047 |
but you'll usually also set :setting:`USE_TZ` to ``True`` so that conversion |
| 3048 |
to local time happens by default. |
| 3049 |
|
| 3050 |
See :ref:`time-zones-in-templates`. |
| 3051 |
|
| 3052 |
Other tags and filters libraries |
| 3053 |
================================ |
| 3054 |
|
| 3055 |
Django comes with a couple of other template-tag libraries that you have to |
| 3056 |
enable explicitly in your :setting:`INSTALLED_APPS` setting and enable in your |
| 3057 |
template with the :ttag:`{% load %}<load>` tag. |
| 3058 |
|
| 3059 |
``django.contrib.humanize`` |
| 3060 |
--------------------------- |
| 3061 |
|
| 3062 |
A set of Django template filters useful for adding a "human touch" to data. See |
| 3063 |
:doc:`/ref/contrib/humanize`. |
| 3064 |
|
| 3065 |
``static`` |
| 3066 |
---------- |
| 3067 |
|
| 3068 |
.. templatetag:: static |
| 3069 |
|
| 3070 |
``static`` |
| 3071 |
~~~~~~~~~~ |
| 3072 |
|
| 3073 |
To link to static files that are saved in :setting:`STATIC_ROOT` Django ships |
| 3074 |
with a :ttag:`static` template tag. If the :mod:`django.contrib.staticfiles` |
| 3075 |
app is installed, the tag will serve files using ``url()`` method of the |
| 3076 |
storage specified by ``staticfiles`` in :setting:`STORAGES`. For example: |
| 3077 |
|
| 3078 |
.. code-block:: html+django |
| 3079 |
|
| 3080 |
{% load static %} |
| 3081 |
<img src="{% static 'images/hi.jpg' %}" alt="Hi!"> |
| 3082 |
|
| 3083 |
It is also able to consume standard context variables, e.g. assuming a |
| 3084 |
``user_stylesheet`` variable is passed to the template: |
| 3085 |
|
| 3086 |
.. code-block:: html+django |
| 3087 |
|
| 3088 |
{% load static %} |
| 3089 |
<link rel="stylesheet" href="{% static user_stylesheet %}" media="screen"> |
| 3090 |
|
| 3091 |
If you'd like to retrieve a static URL without displaying it, you can use a |
| 3092 |
slightly different call: |
| 3093 |
|
| 3094 |
.. code-block:: html+django |
| 3095 |
|
| 3096 |
{% load static %} |
| 3097 |
{% static "images/hi.jpg" as myphoto %} |
| 3098 |
<img src="{{ myphoto }}" alt="Hi!"> |
| 3099 |
|
| 3100 |
.. admonition:: Using Jinja2 templates? |
| 3101 |
|
| 3102 |
See :class:`~django.template.backends.jinja2.Jinja2` for information on |
| 3103 |
using the ``static`` tag with Jinja2. |
| 3104 |
|
| 3105 |
.. templatetag:: get_static_prefix |
| 3106 |
|
| 3107 |
``get_static_prefix`` |
| 3108 |
~~~~~~~~~~~~~~~~~~~~~ |
| 3109 |
|
| 3110 |
You should prefer the :ttag:`static` template tag, but if you need more control |
| 3111 |
over exactly where and how :setting:`STATIC_URL` is injected into the template, |
| 3112 |
you can use the :ttag:`get_static_prefix` template tag: |
| 3113 |
|
| 3114 |
.. code-block:: html+django |
| 3115 |
|
| 3116 |
{% load static %} |
| 3117 |
<img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!"> |
| 3118 |
|
| 3119 |
There's also a second form you can use to avoid extra processing if you need |
| 3120 |
the value multiple times: |
| 3121 |
|
| 3122 |
.. code-block:: html+django |
| 3123 |
|
| 3124 |
{% load static %} |
| 3125 |
{% get_static_prefix as STATIC_PREFIX %} |
| 3126 |
|
| 3127 |
<img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi!"> |
| 3128 |
<img src="{{ STATIC_PREFIX }}images/hi2.jpg" alt="Hello!"> |
| 3129 |
|
| 3130 |
.. templatetag:: get_media_prefix |
| 3131 |
|
| 3132 |
``get_media_prefix`` |
| 3133 |
~~~~~~~~~~~~~~~~~~~~ |
| 3134 |
|
| 3135 |
Similar to the :ttag:`get_static_prefix`, ``get_media_prefix`` populates a |
| 3136 |
template variable with the media prefix :setting:`MEDIA_URL`, e.g.: |
| 3137 |
|
| 3138 |
.. code-block:: html+django |
| 3139 |
|
| 3140 |
{% load static %} |
| 3141 |
<body data-media-url="{% get_media_prefix %}"> |
| 3142 |
|
| 3143 |
By storing the value in a data attribute, we ensure it's escaped appropriately |
| 3144 |
if we want to use it in a JavaScript context. |