python / expert
Snippet
Django Custom Template Tags and Filters with Inclusion Tags
Django's template system allows custom template tags and filters to extend its capabilities. Custom filters transform template variables before rendering using the @register.filter decorator. Inclusion tags render template partials with context data using @register.inclusion_tag for reusable components like pagination. Simple tags provide utility functions accessible anywhere in templates with @register.simple_tag. All custom tags must be loaded in templates via {% load custom_tags %}.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django import templatefrom django.utils.safestring import mark_saferegister = template.Library()@register.filter(name='truncate_words_middle')def truncate_words_middle(text, num_words):words = text.split()if len(words) <= num_words:return textstart = words[:num_words//2]end = words[-num_words//2:]return ' '.join(start) + '...' + ' '.join(end)@register.inclusion_tag('components/pagination.html')def render_pagination(page_obj, request_get_param='page'):return {'page_obj': page_obj,'request_get_param': request_get_param}@register.simple_tagdef get_range(start, end, step=1):return list(range(start, end, step))
django
Breakdown
1
from django.utils.safestring import mark_safe
Imports mark_safe to return HTML content that should not be escaped
2
@register.filter(name='truncate_words_middle')
Decorator registers custom filter with optional custom name
3
words = text.split()
Splits text into words to enable middle truncation logic
4
start = words[:num_words//2]
Takes first half of words for truncation start segment
5
@register.inclusion_tag('components/pagination.html')
Decorator specifies template file to render with returned context
6
@register.simple_tag
Decorator registers tag without template, returns value directly