Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 77 ยท Templates

Built-in Template Tags and Filters Catalog

A practical catalog of Django's built-in template tags and filters: regroup, cycle, firstof, with, verbatim, lorem, widthratio, dictsort, filesizeformat, timesince and the in, is operators, all run live.

Django Templates introduced variables, filters and the common tags (for, if, url, include). Django ships far more than that, and knowing the full list saves you from writing custom code for things the template language already does. This lesson is a tour of the useful ones, grouped by purpose, with output you can run and change.

The examples render templates directly with Django's template engine from Python strings, so you see exactly what each construct produces. In your own project the same text lives in .html files. (Python's tzdata package is installed first, because a few date tags need a time zone database in the browser.)

Tags: structure and repetition

A tag is written {% name arguments %} and some come in pairs ({% with %} ... {% endwith %}). The first group helps you lay out repeated content.

Tag What it does
{% regroup list by field as groups %} Groups consecutive items by a field. Sort the list by that field first
{% cycle 'a' 'b' %} Returns the next value on each pass, usually for striped rows. as name stores it, {% resetcycle %} restarts
{% ifchanged value %} Renders its body only when the value differs from the previous loop pass
{% firstof a b 'fallback' %} Prints the first value that is not "falsey" (a one-line version of if/elif/else)
{% with x=expensive.call %} Names a value once, instead of repeating a costly lookup
{% widthratio value max 100 %} Computes value / max * 100, rounded: handy for progress bars
{% now "Y" %} Prints the current date or time in a given format; as var stores it
{% lorem 3 w %} Placeholder text: w words, p paragraphs, b plain paragraphs
{% verbatim %}...{% endverbatim %} Stops Django from interpreting its contents (for JavaScript frameworks that also use {{ }})
{% templatetag openblock %} Prints a literal template delimiter such as {%
{% spaceless %}...{% endspaceless %} Removes whitespace between HTML tags
{% comment %}...{% endcomment %} or {# ... #} Comments that never reach the browser

Most of these shine on real data. The example below feeds a list of cities to regroup, cycle, ifchanged, firstof, with and widthratio:

Python Built-in tags in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notes on a few results. regroup produced three groups because the cities were already sorted by country; unsorted input would create a new group at every change, which is the usual surprise. cycle alternated odd and even row by row. firstof skipped the empty string and 0 because both are false in a template test. widthratio is integer-friendly: 30 of 120 gives 25.

Operators in {% if %}

Besides and, or, not and the comparisons you know, if supports:

  • in and not in: {% if "a" in word %}, {% if user not in banned %}
  • is and is not: identity tests such as {% if value is None %} or {% if flag is not True %}

Use is None to tell "no value" apart from 0 or an empty string. Mixing and with or without parentheses is not supported (Django has no parentheses in if); and binds more tightly than or.

Filters: shaping values

A filter transforms a value: {{ value|filter:argument }}. You can chain them from left to right. Here are the ones worth remembering, by purpose.

Purpose Filters
Text size and shape truncatechars:8, truncatewords:5, wordcount, center:11, ljust:8, rjust:8, linenumbers
Cleaning cut:" " (removes a substring), addslashes, striptags, escape, force_escape, urlize, slugify
Lists first, last, join:", ", slice:":3", make_list, dictsort:"key", dictsortreversed:"key", unordered_list, random
Numbers floatformat:2, intcomma (needs humanize), filesizeformat, divisibleby:3, add:5, stringformat:"05d"
Dates date:"D, d M Y", time:"H:i", timesince, timeuntil
Defaults and booleans default:"-", default_if_none:"-", yesno:"on,off,unknown", pluralize

(The old length_is filter was removed in Django 5.1: write {% if items|length == 3 %} instead.)

Python Built-in filters in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few outputs deserve a closer look:

  • timesince reports the two most significant units (2 days, 1 hour), which is why you never see seconds on an old date. Pass a second argument to compare against a date other than "now", which also makes the result deterministic for tests.
  • floatformat with no argument rounds to one decimal (34.2), floatformat:0 to a whole number (34), and floatformat:2 always pads (7.00).
  • 1-is-not-True printed because the integer 1 is equal to True but is not the object True. That is the difference between == and is.
  • striptags removes tags but is not a security tool for untrusted HTML. Rely on automatic escaping (see Escaping and safety) for output, and a proper sanitizer library if you must accept HTML.

Where to look when you need something else

  • django.contrib.humanize adds intcomma, naturalday, naturaltime and ordinal; it is covered in Useful contrib Apps.
  • {% load i18n %}, {% load l10n %}, {% load static %} and {% load cache %} unlock tag libraries for translations, localized values, static files and fragment caching.
  • Django 6.0 added {% partialdef %} and {% partial %} to name and reuse a block within a template.
  • A tag or filter you wish existed is usually a few lines in a custom tag library.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does {% regroup %} sometimes create more groups than expected?

    regroup starts a new group each time the field changes between neighbours. Sort the list by that field in the view or queryset.
  2. 2. Which tag prints text that Django must NOT interpret, for example JavaScript template syntax?

    verbatim outputs its contents as is, so {{ }} and {% %} inside are not processed by Django.
  3. 3. What does {% widthratio 30 120 100 %} output?

    It computes 30 / 120 * 100 and rounds to an integer: 25. It is useful for progress bar widths.
  4. 4. What does {% if value is None %} distinguish that {% if not value %} does not?

    not value is true for many values. is None is true only for None itself.

Summary

  • Layout tags: regroup (needs ordered input), cycle, ifchanged, firstof, with, widthratio, now, lorem, verbatim, spaceless and templatetag.
  • {% if %} supports in, not in, is and is not in addition to comparisons and boolean logic.
  • Filters shape text, lists, numbers and dates; chain them left to right, and use dictsort, slice, unordered_list, filesizeformat, timesince and yesno instead of hand-written view code.
  • Extra libraries such as humanize, i18n and static are one {% load %} away; write a custom tag only when nothing built in fits.

Next: Template Inheritance and Includes.