Filters are applied to template variables using the | pipe character.
Strings
{{ name|lower }} <!-- dmitrii -->
{{ name|upper }} <!-- DMITRII -->
{{ name|title }} <!-- Dmitrii Masliaev -->
{{ name|capfirst }} <!-- Dmitrii -->
{{ text|truncatewords:10 }} <!-- first 10 words... -->
{{ text|truncatechars:50 }} <!-- first 50 characters... -->
{{ text|wordcount }} <!-- word count -->
{{ html|striptags }} <!-- strip HTML tags -->
{{ text|linebreaks }} <!-- \n → <p> -->
{{ text|linebreaksbr }} <!-- \n → <br> -->
Numbers
{{ price|floatformat:2 }} <!-- 1234.56 -->
{{ count|pluralize }} <!-- "s" or "" -->
{{ count|pluralize:"ий,ия,ий" }} <!-- declension -->
{{ number|filesizeformat }} <!-- 1.2 MB -->
Dates
{{ date|date:"d.m.Y" }} <!-- 15.01.2024 -->
{{ date|date:"d M Y" }} <!-- 15 Jan 2024 -->
{{ date|time:"H:i" }} <!-- 10:30 -->
{{ date|timesince }} <!-- 3 days ago -->
{{ date|timeuntil }} <!-- in 2 days -->
Lists and Dictionaries
{{ items|length }} <!-- number of items -->
{{ items|first }} <!-- first item -->
{{ items|last }} <!-- last item -->
{{ items|join:", " }} <!-- comma-separated -->
{{ items|slice:":3" }} <!-- first 3 items -->
{{ items|dictsort:"name" }} <!-- sort by field -->
Logic and Display
{{ value|default:"not specified" }} <!-- if False/None/empty -->
{{ value|default_if_none:"N/A" }} <!-- only if None -->
{{ value|yesno:"yes,no,unknown" }} <!-- True/False/None -->
Security
{{ html|safe }} <!-- do not escape HTML -->
{{ text|escape }} <!-- escape (default behaviour) -->
{{ text|urlize }} <!-- convert URLs to links -->
Custom Filter
# templatetags/my_filters.py
from django import template
register = template.Library()
@register.filter
def priority_label(value):
labels = {1: 'Low', 2: 'Medium', 3: 'High'}
return labels.get(value, value)
{% load my_filters %}
{{ task.priority|priority_label }}
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!