================================== 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 ====================== .. 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. Sample usage: .. code-block:: html+django {% autoescape on %} {{ body }} {% endautoescape %} When auto-escaping is in effect, all content derived from variables has HTML escaping applied before placing the result into the output (but after any filters are applied). This is equivalent to manually applying the :tfilter:`escape` filter to each variable. The only exceptions are variables already marked as "safe" from escaping. Variables could be marked as "safe" by the code which populated the variable, by applying the :tfilter:`safe` or :tfilter:`escape` filters, or because it's the result of a previous filter that marked the string as "safe". Within the scope of disabled auto-escaping, chaining filters, including :tfilter:`escape`, may cause unexpected (but documented) results such as the following: .. code-block:: html+django {% autoescape off %} {{ my_list|join:", "|escape }} {% endautoescape %} The above code will output the joined elements of ``my_list`` unescaped. This is because the filter chaining sequence executes first :tfilter:`join` on ``my_list`` (without applying escaping to each item since ``autoescape`` is ``off``), marking the result as safe. Subsequently, this safe result will be fed to :tfilter:`escape` filter, which does not apply a second round of escaping. In order to properly escape every element in a sequence, use the :tfilter:`escapeseq` filter: .. code-block:: html+django {% autoescape off %} {{ my_list|escapeseq|join:", " }} {% 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: .. code-block:: html+django

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:: csp_nonce_attr ``csp_nonce_attr`` ------------------ .. versionadded:: 6.1 When called without arguments, renders a ``nonce=""`` HTML attribute when the :func:`~django.template.context_processors.csp` context processor is configured, and an empty string otherwise. Use it in `` When called with a :class:`~django.forms.Media` object as the argument, renders its assets with the CSP nonce applied to each `` The resulting data can be accessed in JavaScript like this: .. code-block:: javascript const value = JSON.parse(document.getElementById('hello-data').textContent); XSS attacks are mitigated by escaping the characters "<", ">" and "&". For example if ``value`` is ``{'hello': 'world&'}``, the output is: .. code-block:: html This is compatible with a strict Content Security Policy that prohibits in-page script execution. It also maintains a clean separation between passive data and executable code. .. templatefilter:: last ``last`` -------- Returns the last item in a list. For example: .. code-block:: html+django {{ 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: .. code-block:: html+django {{ value|length }} If ``value`` is ``['a', 'b', 'c', 'd']`` or ``"abcd"``, the output will be ``4``. The filter returns ``0`` for an undefined variable. .. 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 (``

``). For example: .. code-block:: html+django {{ value|linebreaks }} If ``value`` is ``Joel\nis a slug``, the output will be ``

Joel
is a slug

``. .. templatefilter:: linebreaksbr ``linebreaksbr`` ---------------- Converts all newlines in a piece of plain text to HTML line breaks (``
``). For example: .. code-block:: html+django {{ value|linebreaksbr }} If ``value`` is ``Joel\nis a slug``, the output will be ``Joel
is a slug``. .. templatefilter:: linenumbers ``linenumbers`` --------------- Displays text with line numbers. For example: .. code-block:: html+django {{ value|linenumbers }} If ``value`` is: .. code-block:: html+django one two three the output will be: .. code-block:: html+django 1. one 2. two 3. three .. templatefilter:: ljust ``ljust`` --------- Left-aligns the value in a field of a given width. **Argument:** field size For example: .. code-block:: html+django "{{ value|ljust:"10" }}" If ``value`` is ``Django``, the output will be ``"Django "``. .. templatefilter:: lower ``lower`` --------- Converts a string into all lowercase. For example: .. code-block:: html+django {{ value|lower }} If ``value`` is ``Totally LOVING this Album!``, the output will be ``totally loving this album!``. .. templatefilter:: make_list ``make_list`` ------------- Returns the value turned into a list. For a string, it's a list of characters. For an integer, the argument is cast to a string before creating a list. For example: .. code-block:: html+django {{ value|make_list }} If ``value`` is the string ``"Joel"``, the output would be the list ``['J', 'o', 'e', 'l']``. If ``value`` is ``123``, the output will be the list ``['1', '2', '3']``. .. templatefilter:: phone2numeric ``phone2numeric`` ----------------- Converts a phone number (possibly containing letters) to its numerical equivalent. The input doesn't have to be a valid phone number. This will happily convert any string. For example: .. code-block:: html+django {{ value|phone2numeric }} If ``value`` is ``800-COLLECT``, the output will be ``800-2655328``. .. templatefilter:: pluralize ``pluralize`` ------------- Returns a plural suffix if the value is not ``1``, ``'1'``, or an object of length 1. By default, this suffix is ``'s'``. Example: .. code-block:: html+django You have {{ num_messages }} message{{ num_messages|pluralize }}. If ``num_messages`` is ``1``, the output will be ``You have 1 message.`` If ``num_messages`` is ``2`` the output will be ``You have 2 messages.`` For words that require a suffix other than ``'s'``, you can provide an alternate suffix as a parameter to the filter. Example: .. code-block:: html+django You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}. For words that don't pluralize by simple suffix, you can specify both a singular and plural suffix, separated by a comma. Example: .. code-block:: html+django You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}. .. note:: Use :ttag:`blocktranslate` to pluralize translated strings. .. templatefilter:: pprint ``pprint`` ---------- A wrapper around :func:`pprint.pprint` -- for debugging, really. .. templatefilter:: random ``random`` ---------- Returns a random item from the given list. For example: .. code-block:: html+django {{ value|random }} If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``. .. templatefilter:: rjust ``rjust`` --------- Right-aligns the value in a field of a given width. **Argument:** field size For example: .. code-block:: html+django "{{ value|rjust:"10" }}" If ``value`` is ``Django``, the output will be ``" Django"``. .. templatefilter:: safe ``safe`` -------- Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect. .. note:: If you are chaining filters, a filter applied after ``safe`` can make the contents unsafe again. For example, the following code prints the variable as is, unescaped: .. code-block:: html+django {{ var|safe|escape }} .. templatefilter:: safeseq ``safeseq`` ----------- Applies the :tfilter:`safe` filter to each element of a sequence. Useful in conjunction with other filters that operate on sequences, such as :tfilter:`join`. For example: .. code-block:: html+django {{ some_list|safeseq|join:", " }} You couldn't use the :tfilter:`safe` filter directly in this case, as it would first convert the variable into a string, rather than working with the individual elements of the sequence. .. templatefilter:: slice ``slice`` --------- Returns a slice of the list. Uses the same syntax as Python's list slicing. See the `Python documentation `_ for an introduction. Example: .. code-block:: html+django {{ some_list|slice:":2" }} If ``some_list`` is ``['a', 'b', 'c']``, the output will be ``['a', 'b']``. .. templatefilter:: slugify ``slugify`` ----------- Converts to ASCII. Converts spaces to hyphens. Removes characters that aren't alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace. For example: .. code-block:: html+django {{ value|slugify }} If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``. .. templatefilter:: stringformat ``stringformat`` ---------------- Formats the variable according to the argument, a string formatting specifier. This specifier uses the :ref:`old-string-formatting` syntax, with the exception that the leading "%" is dropped. For example: .. code-block:: html+django {{ value|stringformat:"E" }} If ``value`` is ``10``, the output will be ``1.000000E+01``. .. templatefilter:: striptags ``striptags`` ------------- Makes all possible efforts to strip all [X]HTML tags. For example: .. code-block:: html+django {{ value|striptags }} If ``value`` is ``"Joel a slug"``, the output will be ``"Joel is a slug"``. .. admonition:: No safety guarantee Note that ``striptags`` doesn't give any guarantee about its output being HTML safe, particularly with non valid HTML input. So **NEVER** apply the ``safe`` filter to a ``striptags`` output. If you are looking for something more robust, consider using a third-party HTML sanitizing tool. .. templatefilter:: time ``time`` -------- Formats a time according to the given format. Given format can be the predefined one :setting:`TIME_FORMAT`, or a custom format, same as the :tfilter:`date` filter. Note that the predefined format is locale-dependent. For example: .. code-block:: html+django {{ value|time:"H:i" }} If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be the string ``"01:23"``. Note that you can backslash-escape a format string if you want to use the "raw" value. In this example, both "h" and "m" are backslash-escaped, because otherwise each is a format string that displays the hour and the month, respectively: .. code-block:: html+django {{ value|time:"H\h i\m" }} This would display as "01h 23m". Another example: Assuming that :setting:`LANGUAGE_CODE` is, for example, ``"de"``, then for: .. code-block:: html+django {{ value|time:"TIME_FORMAT" }} the output will be the string ``"01:23"`` (The ``"TIME_FORMAT"`` format specifier for the ``de`` locale as shipped with Django is ``"H:i"``). The ``time`` filter will only accept parameters in the format string that relate to the time of day, not the date. If you need to format a ``date`` value, use the :tfilter:`date` filter instead (or along with :tfilter:`time` if you need to render a full :class:`~datetime.datetime` value). There is one exception the above rule: When passed a ``datetime`` value with attached timezone information (a :ref:`time-zone-aware ` ``datetime`` instance) the ``time`` filter will accept the timezone-related :ref:`format specifiers ` ``'e'``, ``'O'`` , ``'T'`` and ``'Z'``. When used without a format string, the ``TIME_FORMAT`` format specifier is used: .. code-block:: html+django {{ value|time }} is the same as: .. code-block:: html+django {{ value|time:"TIME_FORMAT" }} .. templatefilter:: timesince ``timesince`` ------------- Formats a date as the time since that date (e.g., "4 days, 6 hours"). Takes an optional argument that is a variable containing the date to use as the comparison point (without the argument, the comparison point is *now*). For example, if ``blog_date`` is a date instance representing midnight on 1 June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006, then the following would return "8 hours": .. code-block:: html+django {{ blog_date|timesince:comment_date }} Comparing offset-naive and offset-aware datetimes will return an empty string. Minutes is the smallest unit used, and "0 minutes" will be returned for any date that is in the future relative to the comparison point. .. templatefilter:: timeuntil ``timeuntil`` ------------- Similar to ``timesince``, except that it measures the time from now until the given date or datetime. For example, if today is 1 June 2006 and ``conference_date`` is a date instance holding 29 June 2006, then ``{{ conference_date|timeuntil }}`` will return "4 weeks". Takes an optional argument that is a variable containing the date to use as the comparison point (instead of *now*). If ``from_date`` contains 22 June 2006, then the following will return "1 week": .. code-block:: html+django {{ conference_date|timeuntil:from_date }} Comparing offset-naive and offset-aware datetimes will return an empty string. Minutes is the smallest unit used, and "0 minutes" will be returned for any date that is in the past relative to the comparison point. .. templatefilter:: title ``title`` --------- Converts a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This tag makes no effort to keep "trivial words" in lowercase. For example: .. code-block:: html+django {{ value|title }} If ``value`` is ``"my FIRST post"``, the output will be ``"My First Post"``. .. templatefilter:: truncatechars ``truncatechars`` ----------------- Truncates a string if it is longer than the specified number of characters. Truncated strings will end with a translatable ellipsis character ("…"). **Argument:** Number of characters to truncate to For example: .. code-block:: html+django {{ value|truncatechars:7 }} If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel i…"``. .. templatefilter:: truncatechars_html ``truncatechars_html`` ---------------------- Similar to :tfilter:`truncatechars`, except that it is aware of HTML tags. Any tags that are opened in the string and not closed before the truncation point are closed immediately after the truncation. For example: .. code-block:: html+django {{ value|truncatechars_html:7 }} If ``value`` is ``"

Joel is a slug

"``, the output will be ``"

Joel i…

"``. Newlines in the HTML content will be preserved. .. admonition:: Size of input string Processing large, potentially malformed HTML strings can be resource-intensive and impact service performance. .. templatefilter:: truncatewords ``truncatewords`` ----------------- Truncates a string after a certain number of words. **Argument:** Number of words to truncate after For example: .. code-block:: html+django {{ value|truncatewords:2 }} If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is …"``. Newlines within the string will be removed. .. templatefilter:: truncatewords_html ``truncatewords_html`` ---------------------- Similar to :tfilter:`truncatewords`, except that it is aware of HTML tags. Any tags that are opened in the string and not closed before the truncation point, are closed immediately after the truncation. This is less efficient than :tfilter:`truncatewords`, so should only be used when it is being passed HTML text. For example: .. code-block:: html+django {{ value|truncatewords_html:2 }} If ``value`` is ``"

Joel is a slug

"``, the output will be ``"

Joel is …

"``. Newlines in the HTML content will be preserved. .. admonition:: Size of input string Processing large, potentially malformed HTML strings can be resource-intensive and impact service performance. .. templatefilter:: unordered_list ``unordered_list`` ------------------ Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing ``
    `` tags. The list is assumed to be in the proper format. For example, if ``var`` contains ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then ``{{ var|unordered_list }}`` would return: .. code-block:: html+django
  • States
    • Kansas
      • Lawrence
      • Topeka
    • Illinois
  • .. templatefilter:: upper ``upper`` --------- Converts a string into all uppercase. For example: .. code-block:: html+django {{ value|upper }} If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``. .. templatefilter:: urlencode ``urlencode`` ------------- Escapes a value for use in a URL. For example: .. code-block:: html+django {{ value|urlencode }} If ``value`` is ``"https://www.example.org/foo?a=b&c=d"``, the output will be ``"https%3A//www.example.org/foo%3Fa%3Db%26c%3Dd"``. An optional argument containing the characters which should not be escaped can be provided. If not provided, the '/' character is assumed safe. An empty string can be provided when *all* characters should be escaped. For example: .. code-block:: html+django {{ value|urlencode:"" }} If ``value`` is ``"https://www.example.org/"``, the output will be ``"https%3A%2F%2Fwww.example.org%2F"``. .. templatefilter:: urlize ``urlize`` ---------- Converts URLs and email addresses in text into clickable links. This template tag works on links prefixed with ``http://``, ``https://``, or ``www.``. For example, ``https://djangocon.eu`` will get converted but ``djangocon.eu`` won't. It also supports domain-only links ending in one of the original top level domains (``.com``, ``.edu``, ``.gov``, ``.int``, ``.mil``, ``.net``, and ``.org``). For example, ``djangoproject.com`` gets converted. Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens), and ``urlize`` will still do the right thing. Links generated by ``urlize`` have a ``rel="nofollow"`` attribute added to them. For example: .. code-block:: html+django {{ value|urlize }} If ``value`` is ``"Check out www.djangoproject.com"``, the output will be: .. code-block:: html+django Check out www.djangoproject.com .. deprecated:: 6.0 The default protocol when none is provided will change from HTTP to HTTPS in Django 7.0. Hence, the output will become: .. code-block:: html+django Check out www.djangoproject.com Set the transitional setting :setting:`URLIZE_ASSUME_HTTPS` to ``True`` to opt into using HTTPS during the Django 6.x release cycle. In addition to web links, ``urlize`` also converts email addresses into ``mailto:`` links. If ``value`` is ``"Send questions to foo@example.com"``, the output will be ``"Send questions to foo@example.com"``. The ``urlize`` filter also takes an optional parameter ``autoescape``. If ``autoescape`` is ``True``, the link text and URLs will be escaped using Django's built-in :tfilter:`escape` filter. The default value for ``autoescape`` is ``True``. .. note:: If ``urlize`` is applied to text that already contains HTML markup, or to email addresses that contain single quotes (``'``), things won't work as expected. Apply this filter only to plain text. .. templatefilter:: urlizetrunc ``urlizetrunc`` --------------- Converts URLs and email addresses into clickable links just like urlize_, but truncates URLs longer than the given character limit. **Argument:** Number of characters that link text should be truncated to, including the ellipsis that's added if truncation is necessary. For example: .. code-block:: html+django {{ value|urlizetrunc:15 }} If ``value`` is ``"Check out www.djangoproject.com"``, the output would be: .. code-block:: html+django Check out www.djangoproj… .. deprecated:: 6.0 The default protocol when none is provided will change from HTTP to HTTPS in Django 7.0. Hence, the output will become: .. code-block:: html+django Check out www.djangoproj… Set the transitional setting :setting:`URLIZE_ASSUME_HTTPS` to ``True`` to opt into using HTTPS during the Django 6.x release cycle. As with urlize_, this filter should only be applied to plain text. .. templatefilter:: wordcount ``wordcount`` ------------- Returns the number of words. For example: .. code-block:: html+django {{ value|wordcount }} If ``value`` is ``"Joel is a slug"``, the output will be ``4``. .. templatefilter:: wordwrap ``wordwrap`` ------------ Wraps words at specified line length. **Argument:** number of characters at which to wrap the text For example: .. code-block:: html+django {{ value|wordwrap:5 }} If ``value`` is ``Joel is a slug``, the output would be: .. code-block:: html+django Joel is a slug .. templatefilter:: yesno ``yesno`` --------- Maps values for ``True``, ``False``, and (optionally) ``None``, to the strings "yes", "no", "maybe", or a custom mapping passed as a comma-separated list, and returns one of those strings according to the value: For example: .. code-block:: html+django {{ value|yesno:"yeah,no,maybe" }} ========== ====================== =========================================== Value Argument Outputs ========== ====================== =========================================== ``True`` ``yes`` ``True`` ``"yeah,no,maybe"`` ``yeah`` ``False`` ``"yeah,no,maybe"`` ``no`` ``None`` ``"yeah,no,maybe"`` ``maybe`` ``None`` ``"yeah,no"`` ``no`` (converts ``None`` to ``False`` if no mapping for ``None`` is given) ========== ====================== =========================================== Internationalization tags and filters ===================================== Django provides template tags and filters to control each aspect of :doc:`internationalization ` in templates. They allow for granular control of translations, formatting, and time zone conversions. ``i18n`` -------- This library allows specifying translatable text in templates. To enable it, set :setting:`USE_I18N` to ``True``, then load it with ``{% load i18n %}``. See :ref:`specifying-translation-strings-in-template-code`. ``l10n`` -------- This library provides control over the localization of values in templates. You only need to load the library using ``{% load l10n %}``. See :ref:`topic-l10n-templates`. ``tz`` ------ This library provides control over time zone conversions in templates. Like ``l10n``, you only need to load the library using ``{% load tz %}``, but you'll usually also set :setting:`USE_TZ` to ``True`` so that conversion to local time happens by default. See :ref:`time-zones-in-templates`. Other tags and filters libraries ================================ Django comes with a couple of other template-tag libraries that you have to enable explicitly in your :setting:`INSTALLED_APPS` setting and enable in your template with the :ttag:`{% load %}` tag. ``django.contrib.humanize`` --------------------------- A set of Django template filters useful for adding a "human touch" to data. See :doc:`/ref/contrib/humanize`. ``static`` ---------- .. templatetag:: static ``static`` ~~~~~~~~~~ To link to static files that are saved in :setting:`STATIC_ROOT` Django ships with a :ttag:`static` template tag. If the :mod:`django.contrib.staticfiles` app is installed, the tag will serve files using ``url()`` method of the storage specified by ``staticfiles`` in :setting:`STORAGES`. For example: .. code-block:: html+django {% load static %} Hi! It is also able to consume standard context variables, e.g. assuming a ``user_stylesheet`` variable is passed to the template: .. code-block:: html+django {% load static %} If you'd like to retrieve a static URL without displaying it, you can use a slightly different call: .. code-block:: html+django {% load static %} {% static "images/hi.jpg" as myphoto %} Hi! .. admonition:: Using Jinja2 templates? See :class:`~django.template.backends.jinja2.Jinja2` for information on using the ``static`` tag with Jinja2. .. templatetag:: get_static_prefix ``get_static_prefix`` ~~~~~~~~~~~~~~~~~~~~~ You should prefer the :ttag:`static` template tag, but if you need more control over exactly where and how :setting:`STATIC_URL` is injected into the template, you can use the :ttag:`get_static_prefix` template tag: .. code-block:: html+django {% load static %} Hi! There's also a second form you can use to avoid extra processing if you need the value multiple times: .. code-block:: html+django {% load static %} {% get_static_prefix as STATIC_PREFIX %} Hi! Hello! .. templatetag:: get_media_prefix ``get_media_prefix`` ~~~~~~~~~~~~~~~~~~~~ Similar to the :ttag:`get_static_prefix`, ``get_media_prefix`` populates a template variable with the media prefix :setting:`MEDIA_URL`, e.g.: .. code-block:: html+django {% load static %} By storing the value in a data attribute, we ensure it's escaped appropriately if we want to use it in a JavaScript context.