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