The Django template system has built-in tags and filters, which are functions inside template to render content in a specific way. Multiple filters can be specified with pipes and filters can have arguments, just as in variable syntax.
{{ "MAINROAD 3222"|lower }} # mainroad 3222
{{ 10|add:15}} # 25
{{ "super"|add:"glue" }} # superglue
{{ "A7"|add:"00" }} # A700
{{ myDate | date:"D d M Y"}} # Wed 20 Jul 2016
A list of available built-in filters can be found at https://docs.djangoproject.com/en/dev/ref/templates/builtins/#ref-templates-builtins-filters .
Creating custom filters
To add your own template filters, create a folder named templatetags
inside your app folder. Then add a __init__.py
, and the file your file that will contain the filters:
#/myapp/templatetags/filters.py
from django import template
register = template.Library()
@register.filter(name='tostring')
def to_string(value):
return str(value)
To actually use the filter you need to load it in your template:
#templates/mytemplate.html
{% load filters %}
{% if customer_id|tostring = customer %} Welcome back {% endif%}
Tricks
Even though the filters seem simple at first, it allows to do some nifty things:
{% for x in ""|ljust:"20" %}Hello World!{% endfor %} # Hello World!Hello World!Hel...
{{ user.name.split|join:"_" }} ## replaces whitespace with '_'
See also template tags for more information.