================================== Built-in template tags and filters ================================== This document describes Django's built-in template tags and filters. It is recommended that you use the :doc:`automatic documentation `, if available, as this will also include documentation for any custom tags or filters installed. .. _ref-templates-builtins-tags: Built-in tag reference ---------------------- .. highlightlang:: html+django .. templatetag:: autoescape autoescape ^^^^^^^^^^ Controls the current auto-escaping behavior. This tag takes either ``on`` or ``off`` as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an ``endautoescape`` ending tag. When auto-escaping is in effect, all variable content has HTML escaping applied to it before placing the result into the output (but after any filters have been applied). This is equivalent to manually applying the :tfilter:`escape` filter to each variable. The only exceptions are variables that are already marked as "safe" from escaping, either by the code that populated the variable, or because it has had the :tfilter:`safe` or :tfilter:`escape` filters applied. Sample usage:: {% autoescape on %} {{ body }} {% endautoescape %} .. templatetag:: block block ^^^^^ Defines a block that can be overridden by child templates. See :ref:`Template inheritance ` for more information. .. templatetag:: comment comment ^^^^^^^ Ignores everything between ``{% comment %}`` and ``{% endcomment %}``. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled. Sample usage::

Rendered text with {{ pub_date|date:"c" }}

{% comment "Optional note" %}

Commented out text with {{ create_date|date:"c" }}

{% endcomment %} ``comment`` tags cannot be nested. .. templatetag:: csrf_token csrf_token ^^^^^^^^^^ This tag is used for CSRF protection, as described in the documentation for :doc:`Cross Site Request Forgeries `. .. templatetag:: cycle cycle ^^^^^ Produces one of its arguments each time this tag is encountered. The first argument is produced on the first encounter, the second argument on the second encounter, and so forth. Once all arguments are exhausted, the tag cycles to the first argument and produces it again. This tag is particularly useful in a loop:: {% for o in some_list %} ... {% endfor %} The first iteration produces HTML that refers to class ``row1``, the second to ``row2``, the third to ``row1`` again, and so on for each iteration of the loop. You can use variables, too. For example, if you have two template variables, ``rowvalue1`` and ``rowvalue2``, you can alternate between their values like this:: {% for o in some_list %} ... {% endfor %} Note that the variables included in the cycle will not be escaped. Any HTML or Javascript code contained in the printed variable will be rendered as-is, which could potentially lead to security issues. So either make sure that you trust their values or use explicit escaping like this:: {% for o in some_list %} ... {% endfor %} You can mix variables and strings:: {% for o in some_list %} ... {% endfor %} In some cases you might want to refer to the current value of a cycle without advancing to the next value. To do this, just give the ``{% cycle %}`` tag a name, using "as", like this:: {% cycle 'row1' 'row2' as rowcolors %} From then on, you can insert the current value of the cycle wherever you'd like in your template by referencing the cycle name as a context variable. If you want to move the cycle to the next value independently of the original ``cycle`` tag, you can use another ``cycle`` tag and specify the name of the variable. So, the following template:: ... ... ... ... would output:: ... ... ... ... You can use any number of values in a ``cycle`` tag, separated by spaces. Values enclosed in single quotes (``'``) or double quotes (``"``) are treated as string literals, while values without quotes are treated as template variables. By default, when you use the ``as`` keyword with the cycle tag, the usage of ``{% cycle %}`` that initiates the cycle will itself produce the first value in the cycle. This could be a problem if you want to use the value in a nested loop or an included template. If you only want to declare the cycle but not produce the first value, you can add a ``silent`` keyword as the last keyword in the tag. For example:: {% for obj in some_list %} {% cycle 'row1' 'row2' as rowcolors silent %} {% include "subtemplate.html" %} {% endfor %} This will output a list of ```` elements with ``class`` alternating between ``row1`` and ``row2``. The subtemplate will have access to ``rowcolors`` in its context and the value will match the class of the ```` that encloses it. If the ``silent`` keyword were to be omitted, ``row1`` and ``row2`` would be emitted as normal text, outside the ```` element. When the silent keyword is used on a cycle definition, the silence automatically applies to all subsequent uses of that specific cycle tag. The following template would output *nothing*, even though the second call to ``{% cycle %}`` doesn't specify ``silent``:: {% cycle 'row1' 'row2' as rowcolors silent %} {% cycle rowcolors %} For backward compatibility, the ``{% cycle %}`` tag supports the much inferior old syntax from previous Django versions. You shouldn't use this in any new projects, but for the sake of the people who are still using it, here's what it looks like:: {% cycle row1,row2,row3 %} In this syntax, each value gets interpreted as a literal string, and there's no way to specify variable values. Or literal commas. Or spaces. Did we mention you shouldn't use this syntax in any new projects? .. versionchanged:: 1.6 To improve safety, future versions of ``cycle`` will automatically escape their output. You're encouraged to activate this behavior by loading ``cycle`` from the ``future`` template library:: {% load cycle from future %} When using the ``future`` version, you can disable auto-escaping with:: {% for o in some_list %} ... {% endfor %} .. templatetag:: debug debug ^^^^^ Outputs a whole load of debugging information, including the current context and imported modules. .. templatetag:: extends extends ^^^^^^^ Signals that this template extends a parent template. This tag can be used in two ways: * ``{% extends "base.html" %}`` (with quotes) uses the literal value ``"base.html"`` as the name of the parent template to extend. * ``{% extends variable %}`` uses the value of ``variable``. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a ``Template`` object, Django will use that object as the parent template. See :ref:`template-inheritance` for more information. .. templatetag:: filter filter ^^^^^^ Filters the contents of the block through one or more filters. Multiple filters can be specified with pipes and filters can have arguments, just as in variable syntax. Note that the block includes *all* the text between the ``filter`` and ``endfilter`` tags. Sample usage:: {% filter force_escape|lower %} This text will be HTML-escaped, and will appear in all lowercase. {% endfilter %} .. note:: The :tfilter:`escape` and :tfilter:`safe` filters are not acceptable arguments. Instead, use the :ttag:`autoescape` tag to manage autoescaping for blocks of template code. .. templatetag:: firstof firstof ^^^^^^^ Outputs the first argument variable that is not False. This tag does *not* auto-escape variable values. Outputs nothing if all the passed variables are False. Sample usage:: {% firstof var1 var2 var3 %} This is equivalent to:: {% if var1 %} {{ var1|safe }} {% elif var2 %} {{ var2|safe }} {% elif var3 %} {{ var3|safe }} {% endif %} You can also use a literal string as a fallback value in case all passed variables are False:: {% firstof var1 var2 var3 "fallback value" %} Note that currently the variables included in the firstof tag will not be escaped. Any HTML or Javascript code contained in the printed variable will be rendered as-is, which could potentially lead to security issues. If you need to escape the variables in the firstof tag, you must do so explicitly:: {% filter force_escape %} {% firstof var1 var2 var3 "fallback value" %} {% endfilter %} .. versionchanged:: 1.6 To improve safety, future versions of ``firstof`` will automatically escape their output. You're encouraged to activate this behavior by loading ``firstof`` from the ``future`` template library:: {% load firstof from future %} When using the ``future`` version, you can disable auto-escaping with:: {% autoescape off %} {% firstof var1 var2 var3 "fallback value" %} {% endautoescape %} Or if only some variables should be escaped, you can use:: {% firstof var1 var2|safe var3 "fallback value"|safe %} .. templatetag:: for for ^^^ Loops over each item in an array, making the item available in a context variable. For example, to display a list of athletes provided in ``athlete_list``:: You can loop over a list in reverse by using ``{% for obj in list reversed %}``. If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of (x,y) coordinates called ``points``, you could use the following to output the list of points:: {% for x, y in points %} There is a point at {{ x }},{{ y }} {% endfor %} This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary ``data``, the following would display the keys and values of the dictionary:: {% for key, value in data.items %} {{ key }}: {{ value }} {% endfor %} The for loop sets a number of variables available within the loop: ========================== =============================================== Variable Description ========================== =============================================== ``forloop.counter`` The current iteration of the loop (1-indexed) ``forloop.counter0`` The current iteration of the loop (0-indexed) ``forloop.revcounter`` The number of iterations from the end of the loop (1-indexed) ``forloop.revcounter0`` The number of iterations from the end of the loop (0-indexed) ``forloop.first`` True if this is the first time through the loop ``forloop.last`` True if this is the last time through the loop ``forloop.parentloop`` For nested loops, this is the loop surrounding the current one ========================== =============================================== for ... empty ^^^^^^^^^^^^^ The ``for`` tag can take an optional ``{% empty %}`` clause whose text is displayed if the given array is empty or could not be found::