0
0
Djangoframework~5 mins

Custom template filters in Django

Choose your learning style9 modes available
Introduction

Custom template filters let you change or format data in your templates easily. They help you show data exactly how you want.

You want to format dates or numbers in a special way in your template.
You need to change text, like making it uppercase or adding symbols.
You want to create reusable small functions to clean up your template code.
You want to filter or modify lists or strings before showing them.
You want to keep your templates simple by moving logic to filters.
Syntax
Django
from django import template

register = template.Library()

@register.filter(name='filter_name')
def filter_function(value, arg=None):
    # modify value using arg if needed
    return modified_value
Use @register.filter decorator to tell Django this is a template filter.
The filter function takes the value from the template and an optional argument.
Examples
This filter changes text to uppercase.
Django
from django import template

register = template.Library()

@register.filter
def upper_case(value):
    return value.upper()
This filter adds a suffix to the given value.
Django
from django import template

register = template.Library()

@register.filter(name='add_suffix')
def add_suffix(value, suffix):
    return f"{value}{suffix}"
Sample Program

This filter reverses any string you pass to it in the template.

Example usage in template: {{ 'hello'|reverse_string }} will show olleh.

Django
from django import template

register = template.Library()

@register.filter
def reverse_string(value):
    """Reverses the given string."""
    return value[::-1]
OutputSuccess
Important Notes

Always register your filters with register.filter so Django knows about them.

Filters can take one optional argument after the value.

Keep filters simple and focused on one task for easy reuse.

Summary

Custom template filters help you change data display in templates.

Define filters with a function and register them using @register.filter.

Use filters in templates with the pipe symbol, like {{ value|filter_name }}.