python / intermediate
Snippet
Decorating Custom Django Template Filters with Arguments
Custom template filters registered via Library instance allow formatting template variables in Django templates while safely handling positional arguments.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
from django import templateregister = template.Library()@register.filter(name='truncate_chars')def truncate_chars(value, max_length=20):if not isinstance(value, str):return valueif len(value) <= max_length:return valuereturn value[:max_length] + '...'
django
Breakdown
1
register = template.Library()
Creates a Django template library registry to hold custom tags and filters.
2
@register.filter(name='truncate_chars')
Registers the function as a template filter accessible under the specified name.
3
def truncate_chars(value, max_length=20):
Defines the filter receiving the pipe input value and an optional parameter.