Intermediate
How can you create custom template filters in Django?
Custom template filters in Django allow you to modify template variables before rendering them. This feature enhances the presentation of data in templates.
To create a custom filter, follow these steps:
- Create a new file in your app directory, typically named
templatetags/my_filters.py
. - Define a function that takes the input and returns the modified output.
- Register the function as a template filter using
@register.filter
.
Here’s an example of a custom filter that converts text to uppercase:
from django import template
register = template.Library()
@register.filter
def to_uppercase(value):
return value.upper()
After defining the filter, you can use it in your templates like this: {{ my_text|to_uppercase }}
.