.. _ref-templates-builtins:
==================================
Built-in template tags and filters
==================================
This document describes Django's built-in template tags and filters. It is
recommended that you use the :ref:`automatic documentation
...
{% endfor %}
You can use variables, too. For example, if you have two template variables,
``rowvalue1`` and ``rowvalue2``, you can cycle between their values like this::
{% for o in some_list %}
...
{% endfor %}
Yes, you can mix variables and strings::
{% for o in some_list %}
...
{% endfor %}
In some cases you might want to refer to the next value of a cycle from
outside of a loop. 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::
...
...
You can use any number of values in a ``{% cycle %}`` tag, separated by spaces.
Values enclosed in single (``'``) or double quotes (``"``) are treated as
string literals, while values without quotes are treated as template variables.
For backwards 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?
.. templatetag:: debug
debug
~~~~~
Output a whole load of debugging information, including the current context and
imported modules.
.. templatetag:: extends
extends
~~~~~~~
Signal 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
~~~~~~
Filter the contents of the variable through variable filters.
Filters can also be piped through each other, and they can have arguments --
just like in variable syntax.
Sample usage::
{% filter force_escape|lower %}
This text will be HTML-escaped, and will appear in all lowercase.
{% endfilter %}
.. templatetag:: firstof
firstof
~~~~~~~
Outputs the first variable passed that is not False. Outputs nothing if all the
passed variables are False.
Sample usage::
{% firstof var1 var2 var3 %}
This is equivalent to::
{% if var1 %}
{{ var1 }}
{% else %}{% if var2 %}
{{ var2 }}
{% else %}{% if var3 %}
{{ var3 }}
{% endif %}{% endif %}{% 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" %}
.. templatetag:: for
for
~~~
Loop over each item in an array. For example, to display a list of athletes
provided in ``athlete_list``::
{% for athlete in athlete_list %}
You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
.. versionadded:: 1.0
If you need to loop over a list of lists, you can unpack the values
in each sub-list 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 "above" the
current one
========================== ================================================
for ... empty
^^^^^^^^^^^^^
.. versionadded:: 1.1
The ``for`` tag can take an optional ``{% empty %}`` clause that will be
displayed if the given array is empty or could not be found::
{% for athlete in athlete_list %}
The above is equivalent to -- but shorter, cleaner, and possibly faster
than -- the following::
{% if athlete_list %}
{% for athlete in athlete_list %}
.. templatetag:: if
if
~~
The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
exists, is not empty, and is not a false boolean value) the contents of the
block are output::
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% else %}
No athletes.
{% endif %}
In the above, if ``athlete_list`` is not empty, the number of athletes will be
displayed by the ``{{ athlete_list|length }}`` variable.
As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
will be displayed if the test fails.
``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
to negate a given variable::
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes or there are some coaches (OK, so
writing English translations of boolean logic sounds
stupid; it's not our fault).
{% endif %}
{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}
``if`` tags don't allow ``and`` and ``or`` clauses within the same tag, because
the order of logic would be ambiguous. For example, this is invalid::
{% if athlete_list and coach_list or cheerleader_list %}
If you need to combine ``and`` and ``or`` to do advanced logic, just use nested
``if`` tags. For example::
{% if athlete_list %}
{% if coach_list or cheerleader_list %}
We have athletes, and either coaches or cheerleaders!
{% endif %}
{% endif %}
Multiple uses of the same logical operator are fine, as long as you use the
same operator. For example, this is valid::
{% if athlete_list or coach_list or parent_list or teacher_list %}
.. templatetag:: ifchanged
ifchanged
~~~~~~~~~
Check if a value has changed from the last iteration of a loop.
The 'ifchanged' block tag is used within a loop. It has two possible uses.
1. Checks its own rendered contents against its previous state and only
displays the content if it has changed. For example, this displays a list of
days, only displaying the month if it changes::
Archive for {{ year }}
{% for date in days %}
{% ifchanged %}{{ date|date:"F" }}
{% endifchanged %}
{{ date|date:"j" }}
{% endfor %}
2. If given a variable, check whether that variable has changed. For
example, the following shows the date every time it changes, but
only shows the hour if both the hour and the date has changed::
{% for date in days %}
{% ifchanged date.date %} {{ date.date }} {% endifchanged %}
{% ifchanged date.hour date.date %}
{{ date.hour }}
{% endifchanged %}
{% endfor %}
.. templatetag:: ifequal
ifequal
~~~~~~~
Output the contents of the block if the two arguments equal each other.
Example::
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
The arguments can be hard-coded strings, so the following is valid::
{% ifequal user.username "adrian" %}
...
{% endifequal %}
It is only possible to compare an argument to template variables or strings.
You cannot check for equality with Python objects such as ``True`` or
``False``. If you need to test if something is true or false, use the ``if``
tag instead.
.. templatetag:: ifnotequal
ifnotequal
~~~~~~~~~~
Just like ``ifequal``, except it tests that the two arguments are not equal.
.. templatetag:: include
include
~~~~~~~
Loads a template and renders it with the current context. This is a way of
"including" other templates within a template.
The template name can either be a variable or a hard-coded (quoted) string,
in either single or double quotes.
This example includes the contents of the template ``"foo/bar.html"``::
{% include "foo/bar.html" %}
This example includes the contents of the template whose name is contained in
the variable ``template_name``::
{% include template_name %}
An included template is rendered with the context of the template that's
including it. This example produces the output ``"Hello, John"``:
* Context: variable ``person`` is set to ``"john"``.
* Template::
{% include "name_snippet.html" %}
* The ``name_snippet.html`` template::
Hello, {{ person }}
See also: ``{% ssi %}``.
.. templatetag:: load
load
~~~~
Load a custom template tag set.
See :ref:`Custom tag and filter libraries
{% for gender in gender_list %}
Let's walk through this example. ``{% regroup %}`` takes three arguments: the
list you want to regroup, the attribute to group by, and the name of the
resulting list. Here, we're regrouping the ``people`` list by the ``gender``
attribute and calling the result ``gender_list``.
``{% regroup %}`` produces a list (in this case, ``gender_list``) of
**group objects**. Each group object has two attributes:
* ``grouper`` -- the item that was grouped by (e.g., the string "Male" or
"Female").
* ``list`` -- a list of all items in this group (e.g., a list of all people
with gender='Male').
Note that ``{% regroup %}`` does not order its input! Our example relies on
the fact that the ``people`` list was ordered by ``gender`` in the first place.
If the ``people`` list did *not* order its members by ``gender``, the regrouping
would naively display more than one group for a single gender. For example,
say the ``people`` list was set to this (note that the males are not grouped
together):
.. code-block:: python
people = [
{'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
{'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
{'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
{'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
{'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
]
With this input for ``people``, the example ``{% regroup %}`` template code
above would result in the following output:
* Male:
* Bill Clinton
* Unknown:
* Pat Smith
* Female:
* Margaret Thatcher
* Male:
* George Bush
* Female:
* Condoleezza Rice
The easiest solution to this gotcha is to make sure in your view code that the
data is ordered according to how you want to display it.
Another solution is to sort the data in the template using the ``dictsort``
filter, if your data is in a list of dictionaries::
{% regroup people|dictsort:"gender" by gender as gender_list %}
.. templatetag:: spaceless
spaceless
~~~~~~~~~
Removes whitespace between HTML tags. This includes tab
characters and newlines.
Example usage::
{% spaceless %}
{% endspaceless %}
This example would return this HTML::
Only space between *tags* is removed -- not space between tags and text. In
this example, the space around ``Hello`` won't be stripped::
{% spaceless %}
Hello
{% endspaceless %}
.. templatetag:: ssi
ssi
~~~
Output the contents of a given file into the page.
Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
file -- which must be specified using an absolute path -- in the current
page::
{% ssi /home/html/ljworld.com/includes/right_generic.html %}
If the optional "parsed" parameter is given, the contents of the included
file are evaluated as template code, within the current context::
{% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
Note that if you use ``{% ssi %}``, you'll need to define
:setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security measure.
See also: ``{% include %}``.
.. templatetag:: templatetag
templatetag
~~~~~~~~~~~
Output one of the syntax characters used to compose template tags.
Since the template system has no concept of "escaping", to display one of the
bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
================== =======
Argument Outputs
================== =======
``openblock`` ``{%``
``closeblock`` ``%}``
``openvariable`` ``{{``
``closevariable`` ``}}``
``openbrace`` ``{``
``closebrace`` ``}``
``opencomment`` ``{#``
``closecomment`` ``#}``
================== =======
.. templatetag:: url
url
~~~
Returns an absolute URL (i.e., a URL without the domain name) matching a given
view function and optional parameters. This is a way to output links without
violating the DRY principle by having to hard-code URLs in your templates::
{% url path.to.some_view arg1,arg2,name1=value1 %}
The first argument is a path to a view function in the format
``package.package.module.function``. Additional arguments are optional and
should be comma-separated values that will be used as positional and keyword
arguments in the URL. All arguments required by the URLconf should be present.
For example, suppose you have a view, ``app_views.client``, whose URLconf
takes a client ID (here, ``client()`` is a method inside the views file
``app_views.py``). The URLconf line might look like this:
.. code-block:: python
('^client/(\d+)/$', 'app_views.client')
If this app's URLconf is included into the project's URLconf under a path
such as this:
.. code-block:: python
('^clients/', include('project_name.app_name.urls'))
...then, in a template, you can create a link to this view like this::
{% url app_views.client client.id %}
The template tag will output the string ``/clients/client/123/``.
.. versionadded:: 1.0
If you're using :ref:`named URL patterns
{% for item in gender.list %}
Above, if ``this_value`` is 175 and ``max_value`` is 200, the image in the
above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
which is rounded up to 88).
.. templatetag:: with
with
~~~~
.. versionadded:: 1.0
Caches a complex variable under a simpler name. This is useful when accessing
an "expensive" method (e.g., one that hits the database) multiple times.
For example::
{% with business.employees.count as total %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
The populated variable (in the example above, ``total``) is only available
between the ``{% with %}`` and ``{% endwith %}`` tags.
.. _ref-templates-builtins-filters:
Built-in filter reference
-------------------------
.. templatefilter:: add
add
~~~
Adds the argument to the value.
For example::
{{ value|add:"2" }}
If ``value`` is ``4``, then the output will be ``6``.
.. templatefilter:: addslashes
addslashes
~~~~~~~~~~
Adds slashes before quotes. Useful for escaping strings in CSV, for example.
.. templatefilter:: capfirst
capfirst
~~~~~~~~
Capitalizes the first character of the value.
.. templatefilter:: center
center
~~~~~~
Centers the value in a field of a given width.
.. templatefilter:: cut
cut
~~~
Removes all values of arg from the given string.
For example::
{{ value|cut:" "}}
If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``.
.. templatefilter:: date
date
~~~~
Formats a date according to the given format (same as the `now`_ tag).
For example::
{{ value|date:"D d M Y" }}
If ``value`` is a ``datetime`` object (e.g., the result of
``datetime.datetime.now()``), the output will be the string
``'Wed 09 Jan 2008'``.
.. templatefilter:: default
default
~~~~~~~
If value evaluates to ``False``, use given default. Otherwise, use the value.
For example::
{{ value|default:"nothing" }}
If ``value`` is ``""`` (the empty string), the output will be ``nothing``.
.. templatefilter:: default_if_none
default_if_none
~~~~~~~~~~~~~~~
If (and only if) value is ``None``, use given default. Otherwise, use the
value.
Note that if an empty string is given, the default value will *not* be used.
Use the ``default`` filter if you want to fallback for empty strings.
For example::
{{ value|default_if_none:"nothing" }}
If ``value`` is ``None``, the output will be the string ``"nothing"``.
.. templatefilter:: dictsort
dictsort
~~~~~~~~
Takes a list of dictionaries and returns that list sorted by the key given in
the argument.
For example::
{{ value|dictsort:"name" }}
If ``value`` is:
.. code-block:: python
[
{'name': 'zed', 'age': 19},
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
]
then the output would be:
.. code-block:: python
[
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
{'name': 'zed', 'age': 19},
]
.. templatefilter:: dictsortreversed
dictsortreversed
~~~~~~~~~~~~~~~~
Takes a list of dictionaries and returns that list sorted in reverse order by
the key given in the argument. This works exactly the same as the above filter,
but the returned value will be in reverse order.
.. templatefilter:: divisibleby
divisibleby
~~~~~~~~~~~
Returns ``True`` if the value is divisible by the argument.
For example::
{{ value|divisibleby:"3" }}
If ``value`` is ``21``, the output would be ``True``.
.. templatefilter:: escape
escape
~~~~~~
Escapes a string's HTML. Specifically, it makes these replacements:
* ``<`` is converted to ``<``
* ``>`` is converted to ``>``
* ``'`` (single quote) is converted to ``'``
* ``"`` (double quote) is converted to ``"``
* ``&`` is converted to ``&``
The escaping is only applied when the string is output, so it does not matter
where in a chained sequence of filters you put ``escape``: it will always be
applied as though it were the last filter. If you want escaping to be applied
immediately, use the ``force_escape`` filter.
Applying ``escape`` to a variable that would normally have auto-escaping
applied to the result will only result in one round of escaping being done. So
it is safe to use this function even in auto-escaping environments. If you want
multiple escaping passes to be applied, use the ``force_escape`` filter.
.. versionchanged:: 1.0
Due to auto-escaping, the behavior of this filter has changed slightly.
The replacements are only made once, after
all other filters are applied -- including filters before and after it.
.. templatefilter:: escapejs
escapejs
~~~~~~~~
.. versionadded:: 1.0
Escapes characters for use in JavaScript strings. This does *not* make the
string safe for use in HTML, but does protect you from syntax errors when using
templates to generate JavaScript/JSON.
.. templatefilter:: filesizeformat
filesizeformat
~~~~~~~~~~~~~~
Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
``'4.1 MB'``, ``'102 bytes'``, etc).
For example::
{{ value|filesizeformat }}
If ``value`` is 123456789, the output would be ``117.7 MB``.
.. templatefilter:: first
first
~~~~~
Returns the first item in a list.
For example::
{{ value|first }}
If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``.
.. templatefilter:: fix_ampersands
fix_ampersands
~~~~~~~~~~~~~~
.. versionchanged:: 1.0
This is rarely useful as ampersands are now automatically escaped. See escape_ for more information.
Replaces ampersands with ``&`` entities.
For example::
{{ value|fix_ampersands }}
If ``value`` is ``Tom & Jerry``, the output will be ``Tom & Jerry``.
.. templatefilter:: floatformat
floatformat
~~~~~~~~~~~
When used without an argument, rounds a floating-point number to one decimal
place -- but only if there's a decimal part to be displayed. For example:
============ =========================== ========
``value`` Template Output
============ =========================== ========
``34.23234`` ``{{ value|floatformat }}`` ``34.2``
``34.00000`` ``{{ value|floatformat }}`` ``34``
``34.26000`` ``{{ value|floatformat }}`` ``34.3``
============ =========================== ========
If used with a numeric integer argument, ``floatformat`` rounds a number to
that many decimal places. For example:
============ ============================= ==========
``value`` Template Output
============ ============================= ==========
``34.23234`` ``{{ value|floatformat:3 }}`` ``34.232``
``34.00000`` ``{{ value|floatformat:3 }}`` ``34.000``
``34.26000`` ``{{ value|floatformat:3 }}`` ``34.260``
============ ============================= ==========
If the argument passed to ``floatformat`` is negative, it will round a number
to that many decimal places -- but only if there's a decimal part to be
displayed. For example:
============ ================================ ==========
``value`` Template Output
============ ================================ ==========
``34.23234`` ``{{ value|floatformat:"-3" }}`` ``34.232``
``34.00000`` ``{{ value|floatformat:"-3" }}`` ``34``
``34.26000`` ``{{ value|floatformat:"-3" }}`` ``34.260``
============ ================================ ==========
Using ``floatformat`` with no argument is equivalent to using ``floatformat``
with an argument of ``-1``.
.. templatefilter:: force_escape
force_escape
~~~~~~~~~~~~
.. versionadded:: 1.0
Applies HTML escaping to a string (see the ``escape`` filter for details).
This filter is applied *immediately* and returns a new, escaped string. This
is useful in the rare cases where you need multiple escaping or want to apply
other filters to the escaped results. Normally, you want to use the ``escape``
filter.
.. templatefilter:: get_digit
get_digit
~~~~~~~~~
Given a whole number, returns the requested digit, where 1 is the right-most
digit, 2 is the second-right-most digit, etc. Returns the original value for
invalid input (if input or argument is not an integer, or if argument is less
than 1). Otherwise, output is always an integer.
For example::
{{ value|get_digit:"2" }}
If ``value`` is ``123456789``, the output will be ``8``.
.. templatefilter:: iriendcode
iriencode
~~~~~~~~~
Converts an IRI (Internationalized Resource Identifier) to a string that is
suitable for including in a URL. This is necessary if you're trying to use
strings containing non-ASCII characters in a URL.
It's safe to use this filter on a string that has already gone through the
``urlencode`` filter.
.. templatefilter:: join
join
~~~~
Joins a list with a string, like Python's ``str.join(list)``
For example::
{{ value|join:" // " }}
If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string
``"a // b // c"``.
.. templatefilter:: last
last
~~~~
.. versionadded:: 1.0
Returns the last item in a list.
For example::
{{ value|last }}
If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string
``"d"``.
.. templatefilter:: length
length
~~~~~~
Returns the length of the value. This works for both strings and lists.
For example::
{{ value|length }}
If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.
.. templatefilter:: length_is
length_is
~~~~~~~~~
Returns ``True`` if the value's length is the argument, or ``False`` otherwise.
For example::
{{ value|length_is:"4" }}
If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``True``.
.. templatefilter:: linebreaks
linebreaks
~~~~~~~~~~
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``
``) and a new line
followed by a blank line becomes a paragraph break (``
Joel
is a
slug