Custom Template Tags
A snippet showing how to define custom template tags in Django.
# models.py
from django.db import models
class Profile(models.Model):
name = models.CharField(max_length=120)
avatar_url = models.URLField(blank=True, default="")
def __str__(self):
return self.name
# admin.py
from django.contrib import admin
from .models import Profile
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
list_display = ("name", "avatar_url")
# templatetags/ui_tags.py
from django import template
register = template.Library()
@register.simple_tag
def greet(name):
return f"Hello, {name}!"
@register.inclusion_tag("partials/profile_card.html")
def profile_card(profile):
return {"profile": profile}
# templates/partials/profile_card.html
<div class="card">
<img src="{{ profile.avatar_url }}" alt="{{ profile.name }}">
<div class="card-body"><strong>{{ profile.name }}</strong></div>
</div>
# templates/home.html
{% load ui_tags %}
{% greet user.first_name %}
{% profile_card user.profile %}
Explanation:
-
Use
@register.simple_tagto return a string/primitive; good for inline values. -
Use
@register.inclusion_tagto render a sub-template with a context dict. -
Place modules inside
templatetags/and load them with{% load %}.
- Category Templates
- Total Views 1184
- Last Modified 29 January, 2026
- Tags #templates #custom tags #logic #extend
Previous snippet
Template Tags Example
Next snippet