Built-in Template Tags and Filters

Chapter 3 lists a number of the most useful built-in template tags and filters. However, Django ships with many more built-in tags and filters. This appendix provides a summary of all template tags and filters in Django. For more detailed information and use cases, see the Django Project website.

Built-in Tags

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 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 safe or escape filters applied. Sample usage:

{% autoescape on %}
    {{ body }}
{% endautoescape %}

block

Defines a block that can be overridden by child templates. See “template inheritance” in Chapter 3 for more information.

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.

Comment tags cannot be nested.

csrf_token

This tag is used for CSRF protection. For more information on Cross Site Request Forgeries (CSRF) see Chapters 3 and 19.

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 %}
    <tr class="{% cycle 'row1' 'row2' %}">
        ...
    </tr>
{% 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 %}
    <tr class="{% cycle rowvalue1 rowvalue2 %}">
        ...
    </tr>
{% endfor %}
You can also mix variables and strings:

{% for o in some_list %}
    <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
        ...
    </tr>
{% endfor %}

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.

debug

Outputs a whole load of debugging information, including the current context and imported modules.

extends

Signals that this template extends a parent template. This tag can be used in two ways:

  1. {% extends "base.html" %} (with quotes) uses the literal value "base.html" as the name of the parent template to extend.
  2. {% 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.

filter

Filters the contents of the block through one or more filters. See the Built-in Filters section later in this appendix for a list of filters in Django

firstof

Outputs the first argument variable 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 }}
{% elif var2 %}
    {{ var2 }}
{% elif var3 %}
    {{ var3 }}
{% endif %}

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:

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}
</ul>

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 sub list into individual variables. 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 %}

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:

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% empty %}
    <li>Sorry, no athletes in this list.</li>
{% endfor %}
</ul>

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 }}
{% elif athlete_in_locker_room_list %}
    Athletes should be out of the locker room soon!
{% 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 may take one or several {% elif %} clauses, as well as an {% else %} clause that will be displayed if all previous conditions fail. These clauses are optional.

Boolean operators

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 %}

Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or e.g.:

{% if athlete_list and coach_list or cheerleader_list %}

will be interpreted like:

if (athlete_list and coach_list) or cheerleader_list 

Use of actual parentheses in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags.

if tags may also use the operators ==, !=, <, >, <=, >= and in which work as listed in Table E-1.

Table E-1: Boolean Operators in Template Tags

Operator Example
== {% if somevar == ~x~ %} …
!= {% if somevar != ~x~ %} …
< {% if somevar < 100 %} …
> {% if somevar > 10 %} …
<= {% if somevar <= 100 %} …
>= {% if somevar >= 10 %} …
In {% if ~bc~ in ~abcdef~ %}
Complex expressions

All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated – that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:

  • or
  • and
  • not
  • in
  • ==, !=, <, >, <=, >=

This order of precedence follows Python exactly.

Filters

You can also use filters in the if expression. For example:

{% if messages|length >= 100 %}
You have lots of messages today!
{% endif %}

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.
  2. If given one or more variables, check whether any variable has changed.

ifequal

Output the contents of the block if the two arguments equal each other. Example:

{% ifequal user.pk comment.user_id %}
    ...
{% endifequal %}

An alternative to the ifequal tag is to use the if tag and the == operator.

ifnotequal

Just like ifequal, except it tests that the two arguments are not equal. An alternative to the ifnotequal tag is to use the if tag and the != operator.

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:

{% include template_name %} 

or a hard-coded (quoted) string:

{% include "foo/bar.html" %}

load

Loads a custom template tag set. For example, the following template would load all the tags and filters registered in somelibrary and otherlibrary located in package package:

{% load somelibrary package.otherlibrary %}

You can also selectively load individual filters or tags from a library, using the from argument.

In this example, the template tags/filters named foo and bar will be loaded from somelibrary:

{% load foo bar from somelibrary %}

See Custom tag and filter libraries for more information.

lorem

Displays random lorem ipsum Latin text. This is useful for providing sample data in templates. Usage:

{% lorem [count] [method] [random] %}

The {% lorem %} tag can be used with zero, one, two or three arguments. The arguments are:

  1. Count. A number (or variable) containing the number of paragraphs or words to generate (default is 1).
  2. Method. Either w for words, p for HTML paragraphs or b for plain-text paragraph blocks (default is b).
  3. Random. The word random, which if given, does not use the common paragraph (Lorem ipsum dolor sit amet…) when generating text.

For example, {% lorem 2 w random %} will output two random Latin words.

now

Displays the current date and/or time, using a format according to the given string. Such string can contain format specifiers characters as described in the date filter section. Example:

It is {% now "jS F Y H:i" %}

The format passed can also be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT or SHORT_DATETIME_FORMAT. The predefined formats may vary depending on the current locale and if format-localization is enabled, e.g.:

It is {% now "SHORT_DATETIME_FORMAT" %}

regroup

Regroups a list of alike objects by a common attribute.

{% regroup %} produces a list of group objects. Each group object has two attributes:

  • grouper – the item that was grouped by (e.g., the string India or Japan).
  • list – a list of all items in this group (e.g., a list of all cities with country = “India”).

Note that {% regroup %} does not order its input!

Any valid template lookup is a legal grouping attribute for the regroup tag,
including methods, attributes, dictionary keys and list items.

spaceless

Removes whitespace between HTML tags. This includes tab characters and newlines. Example usage:

{% spaceless %}
    <p>
        <a href="foo/">Foo</a>
    </p>
{% endspaceless %}

This example would return this HTML:

<p><a href="foo/">Foo</a></p>

templatetag

Outputs 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:

  • openblock outputs: {%
  • closeblock outputs: %}
  • openvariable outputs: {{
  • closevariable outputs: }}
  • openbrace outputs: {
  • closebrace outputs: }
  • opencomment outputs: {#
  • closecomment outputs: #}

Sample usage:

{% templatetag openblock %} url 'entry_list' {% templatetag closeblock %}

url

Returns an absolute path reference (a URL without the domain name) matching a given view function and optional parameters. Any special characters in the resulting path will be encoded using iri_to_uri(). This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates:

{% url 'some-url-name' v1 v2 %}

The first argument is a path to a view function in the format package.package.module.function. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL.

verbatim

Stops the template engine from rendering the contents of this block tag. A common use is to allow a Javascript template layer that collides with Django’s syntax.

widthratio

For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant. For example:

<img src="bar.png" alt="Bar" height="10" width="{% widthratio this_value max_value ma\
x_width %}" />

with

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 total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

Built-in filters

add

Adds the argument to the value. For example:

{{ value|add:"2" }}

If value is 4, then the output will be 6.

addslashes

Adds slashes before quotes. Useful for escaping strings in CSV, for example. For example:

{{ value|addslashes }}

If value is “I'm using Django”, the output will be “I\'m using Django”.

capfirst

Capitalizes the first character of the value. If the first character is not a letter, this filter has no effect.

center

Centers the value in a field of a given width. For example:

"{{ value|center:"14" }}"

If value is “Django”, the output will be “ Django

cut

Removes all values of arg from the given string.

date

Formats a date according to the given format. Uses a similar format as PHP’s date() function with some differences.

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 “Fri 01 Jul 2016”. The format passed can be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT or SHORT_DATETIME_FORMAT, or a custom format that uses date format specifiers.

default

If value evaluates to False, uses the given default. Otherwise, uses the value. For example:

{{ value|default:"nothing" }}   

default_if_none

If (and only if) value is None, uses the given default. Otherwise, uses the value.

dictsort

Takes a list of dictionaries and returns that list sorted by the key given in the argument. For example:

{{ value|dictsort:"name" }}

dictsortreversed

Takes a list of dictionaries and returns that list sorted in reverse order by the key given in the argument.

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.

escape

Escapes a string’s HTML. Specifically, it makes these replacements:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' (single quote) is converted to &#39;
  • " (double quote) is converted to &quot;
  • & is converted to &amp;

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.

escapejs

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.

filesizeformat

Formats 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.

first

Returns the first item in a list.

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. If used with a numeric integer argument, floatformat rounds a number to that many decimal places.

For example, if value is 34.23234, {{ value|floatformat:3 }} will output 34.232.

get_digit

Given a whole number, returns the requested digit, where 1 is the right-most digit.

iriencode

Converts an IRI (Internationalized Resource Identifier) to a string that is suitable for including in a URL.

join

Joins a list with a string, like Python’s str.join(list).

last

Returns the last item in a list.

length

Returns the length of the value. This works for both strings and lists.

length_is

Returns True if the value’s length is the argument, or False otherwise. For example:

{{ value|length_is:"4" }}

linebreaks

Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (<br />) and a new line followed by a blank line becomes a paragraph break (</p>).

linebreaksbr

Converts all newlines in a piece of plain text to HTML line breaks (<br />).

linenumbers

Displays text with line numbers.

ljust

Left-aligns the value in a field of a given width. For example:

{{ value|ljust:"10" }}

If value is “Django”, the output will be “Django ”.

lower

Converts a string into all lowercase.

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 into an Unicode string before creating a list.

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:

{{ value|phone2numeric }}

If value is 800-COLLECT, the output will be 800-2655328.

pluralize

Returns a plural suffix if the value is not 1. By default, this suffix is “s”.

For words that don’t pluralize by simple suffix, you can specify both a singular and plural suffix, separated by a comma. Example:

You have {{ num_cherries }} cherr{{ num_cherries|pluralize:”y,ies” }}.

pprint

A wrapper around pprint.pprint() – for debugging.

random

Returns a random item from the given list.

rjust

Right-aligns the value in a field of a given width. For example:

{{ value|rjust:"10" }}

If value is “Django”, the output will be “ Django”.

safe

Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect.

safeseq

Applies the safe filter to each element of a sequence. Useful in conjunction with other filters that operate on sequences, such as join. For example:

{{ some_list|safeseq|join:", " }}

You couldn’t use the 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.

slice

Returns a slice of the list. Uses the same syntax as Python’s list slicing.

slugify

Converts to ASCII. Converts spaces to hyphens. Removes characters that aren’t alphanumeric, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.

stringformat

Formats the variable according to the argument, a string formatting specifier. This specifier uses Python string formatting syntax, with the exception that the leading % is dropped.

striptags

Makes all possible efforts to strip all [X]HTML tags. For example:

{{ value|striptags }}

time

Formats a time according to the given format. Given format can be the predefined one TIME_FORMAT, or a custom format, same as the date
filter.

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).

timeuntil

Measures the time from now until the given date or datetime.

title

Converts a string into title case by making words start with an uppercase character and the remaining characters lowercase.

truncatechars

Truncates a string if it is longer than the specified number of characters. Truncated strings will end with a translatable ellipsis sequence (…). For example:

{{ value|truncatechars:9 }}

truncatechars_html

Similar to truncatechars, except that it is aware of HTML tags.

truncatewords

Truncates a string after a certain number of words.

truncatewords_html

Similar to truncatewords, except that it is aware of HTML tags.

unordered_list

Recursively takes a self-nested list and returns an HTML unordered list – without opening and closing tags.

upper

Converts a string into all uppercase.

urlencode

Escapes a value for use in a URL.

urlize

Converts URLs and email addresses in text into clickable links. This template tag works on links prefixed with http://, https://, or www..

urlizetrunc

Converts URLs and email addresses into clickable links just like urlize, but truncates URLs longer than the given character limit. For example:

{{ value|urlizetrunc:15 }}

If value is “Check out www.djangoproject.com”, the output would be “Check out <a href="http://www.djangoproject.com" rel="nofollow">www.djangopr...</a>”. As with urlize, this filter should only be applied to plain text.

wordcount

Returns the number of words.

wordwrap

Wraps words at specified line length.

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:

{{ value|yesno:"yeah,no,maybe" }}

Internationalization Tags and Filters

Django provides template tags and filters to control each aspect of 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 USE_I18N to True, then load it with {% load i18n %}.

l10n

This library provides control over the localization of values in templates. You only need to load the library using {% load l10n %}, but you’ll often set USE_L10N to True so that localization is active by default.

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 USE_TZ to True so that conversion to local time happens by default. See time-zones-in-templates.

Other Tags and Filters Libraries

static

To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. You can use this regardless if you’re using RequestContext or not.

{% load static %}
<img src="{% static "/wp-content/uploads/hi.jpg" %}" alt="Hi!" />

It is also able to consume standard context variables, e.g. assuming a user_stylesheet variable is passed to the template:

{% load static %}
<link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="scr\
een" />

If you’d like to retrieve a static URL without displaying it, you can use a slightly different call:

{% load static %}
{% static "/wp-content/uploads/hi.jpg" as myphoto %}
<img src="{{ myphoto }}"></img>

The staticfiles contrib app also ships with a static template tag which uses staticfiles' STATICFILES_STORAGE to build the URL of the given path (rather than simply using urllib.parse.urljoin() with the STATIC_URL setting and the given path). Use that instead if you have an advanced use case such as using a cloud service to serve static files:

{% load static from staticfiles %}
<img src="{% static "/wp-content/uploads/hi.jpg" %}" alt="Hi!" />

get_static_prefix

You should prefer the static template tag, but if you need more control over exactly where and how STATIC_URL is injected into the template, you can use the get_static_prefix template tag:

{% load static %}
<img src="{% get_static_prefix %}/wp-content/uploads/hi.jpg" alt="Hi!"
/>

There’s also a second form you can use to avoid extra processing if you need the value multiple times:

{% load static %}
{% get_static_prefix as STATIC_PREFIX %}

<img src="{{ STATIC_PREFIX }}/wp-content/uploads/hi.jpg" alt="Hi!"  />
<img src="{{ STATIC_PREFIX }}/wp-content/uploads/hi2.jpg" alt="Hello!" />

get_media_prefix

Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL, e.g.:

<script type="text/javascript" charset="utf-8">
var media_path = '{% get_media_prefix %}';
</script>

Django comes with a couple of other template-tag libraries that you have to enable explicitly in your INSTALLED_APPS setting and enable in your template with the {% load %} tag.