Django
Beginner
1 min read
Custom Template Tags and Filters
Example
# blog/templatetags/blog_extras.py
from django import template
from django.utils.html import format_html
from ..models import Post, Tag
register = template.Library()
# --- Simple filter ---
@register.filter(name='reading_time')
def reading_time(text):
"""Estimate reading time in minutes (200 wpm average)."""
word_count = len(text.split())
minutes = max(1, round(word_count / 200))
return f'{minutes} min read'
# --- Simple tag ---
@register.simple_tag
def total_posts():
"""Return the total number of published posts."""
return Post.published.count()
# --- Inclusion tag ---
@register.inclusion_tag('blog/partials/latest_posts.html')
def show_latest_posts(count=5):
"""Render the latest N posts as a sidebar widget."""
latest = Post.published.order_by('-published_at')[:count]
return {'latest_posts': latest}
# --- Usage in a template ---
# {% load blog_extras %}
#
# <p>{{ post.body|reading_time }}</p>
#
# <p>Total posts: {% total_posts %}</p>
#
# {% show_latest_posts count=3 %}
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django