python / intermediate
Snippet
Django Template Tags and Filters for Dynamic Rendering
Django template tags and filters extend the template language with custom functionality. Filters transform variables before display using pipe syntax. Simple tags accept context and parameters for reusable snippets. Inclusion tags render specific templates with returned context, ideal for recurring components like navigation or widget areas.
snippet.py
python
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
26
27
28
29
from django import templatefrom django.utils.html import format_htmlfrom ..models import Categoryregister = template.Library()@register.filter(name='truncate_chars')def truncate_chars(text, length):if len(text) <= length:return textreturn text[:length].rsplit(' ', 1)[0] + '...'@register.simple_tag(takes_context=True)def user_profile_link(context, user):if not user.is_authenticated:return format_html('<span class="text-muted">Anonymous</span>')return format_html('<a href="/users/{}" class="profile-link">{}</a>',user.id,user.username)@register.inclusion_tag('categories.html')def render_categories(show_empty=False):categories = Category.objects.all()if not show_empty:categories = categories.filter(article_count__gt=0)return {'categories': categories}
django
Breakdown
1
from django import template
Import template library to register custom tags and filters
2
register = template.Library()
Create Library instance to register custom template extensions
3
@register.filter(name='truncate_chars')
Decorator registers function as template filter, optional name parameter renames it
4
return text[:length].rsplit(' ', 1)[0] + '...'
Split from right at space to avoid cutting words mid-sentence
5
@register.simple_tag(takes_context=True)
Simple tag can access template context including request and user object
6
format_html('<a href="/users/{}">{}</a>', ...)
Use format_html to safely escape user content and prevent XSS vulnerabilities
7
@register.inclusion_tag('categories.html')
Renders specified template file with returned dictionary as context