Template Tags & Filters (Django)

Template tags are the {% %} constructs that add logic to Django templates (loops, conditionals, URL reversing), and filters are the | transforms that format values. You can also write custom ones in a templatetags module.

Django

Built-in tags cover most needs: {% if %}/{% for %} for control flow, {% url 'name' %} to reverse a URL, {% include %} to embed another template, {% csrf_token %} in forms, and {% block %}/{% extends %} for inheritance.

Filters format and transform values with a pipe: {{ price|floatformat:2 }}, {{ name|default:'Anonymous' }}, {{ text|length }}, and {{ date|date:'Y-m-d' }}. They chain left to right and many take an argument after a colon.

When the built-ins are not enough, you create custom tags and filters in an app's templatetags/ package, register them with @register.filter or @register.simple_tag, and load them in a template with {% load mytags %}.

Syntax

{% tag %}   {{ value|filter:arg }}   {% load mytags %}

Examples

Python

# blog/templatetags/blog_extras.py
from django import template
register = template.Library()

@register.filter
def shout(value):
    return str(value).upper() + "!"

# template: {% load blog_extras %} {{ name|shout }}

Learn it in a lesson

See also

Back to the Dictionary