python / intermediate
Snippet
Django Custom Template Tags and Filters
Django's template system allows custom template tags and filters through a registration mechanism. Simple filters using @register.filter transform content display (like markdown to HTML), and must return safe strings with mark_safe to prevent XSS. Simple tags @register.simple_tag provide more flexibility for generating complex output or accessing multiple variables. Inclusion tags @register.inclusion_tag render a complete template fragment with passed context, perfect for reusable UI components like badges or cards. All custom tags live in a 'templatetags' directory that must be in INSTALLED_APPS.
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
25
# myapp/templatetags/extras.pyfrom django import templatefrom django.utils.safestring import mark_safeimport markdownregister = template.Library()@register.filter(name='markdown')def markdown_filter(text):return mark_safe(markdown.markdown(text))@register.simple_tagdef user_status(user, mode='short'):if mode == 'full':return f"{user.username} ({user.get_role_display()})"return user.username@register.inclusion_tag('parts/badge.html')def render_badge(label, count, color='primary'):return {'label': label, 'count': count, 'color': color}# Usage in template:# {{ post.content|markdown }}# {% user_status request.user 'full' %}# {% render_badge 'Notifications' notification_count %}
django
Breakdown
1
@register.filter(name='markdown')
Decorator registers a filter function usable with pipe operator in templates
2
mark_safe(markdown.markdown(text))
Marks output as safe HTML - use carefully to prevent XSS vulnerabilities
3
@register.inclusion_tag('parts/badge.html')
Renders specified template with returned dictionary as context variables