Django Classy Tags
django-classy-tags is a Python library that provides a class-based approach to writing custom template tags for Django. It aims to make template tag creation easier, shorter, and more fun by offering an extensible argument parser, significantly reducing boilerplate code while remaining fully compatible with the existing Django templating infrastructure. It is currently at version 4.1.0 and appears to have an active release cadence, with recent updates for Django and Python compatibility.
Warnings
- breaking Support for older Python versions was dropped in major releases. Version 3.0.0 dropped Python 3.5 and 3.6. Version 4.0.0 dropped Python 3.7, while adding support for Python 3.11.
- breaking Support for older Django versions was removed in major releases. Version 2.0.0 dropped Django < 2.2. Version 4.0.0 dropped support for Django < 3.2, and added support for Django 4.1. Version 4.1.0 supports Django 4.2.
- gotcha Unlike some other template tag libraries, django-classy-tags does not automatically register or load your tags. You must explicitly define and register each tag.
- gotcha When subclassing `classytags.helpers.AsTag`, you must define at least one breakpoint in the `Options` class, and the *last* breakpoint must correspond to exactly one argument (typically for the 'as varname' part).
Install
-
pip install django-classy-tags
Imports
- Tag
from classytags.core import Tag
- Options
from classytags.core import Options
- Argument
from classytags.arguments import Argument
- AsTag
from classytags.helpers import AsTag
- InclusionTag
from classytags.helpers import InclusionTag
- template
from django import template
Quickstart
from classytags.core import Tag
from django import template
register = template.Library()
class HelloWorldTag(Tag):
name = 'hello_world'
def render_tag(self, context):
return 'Hello, classy world!'
register.tag(HelloWorldTag)
# In your Django template (.html file):
# {% load my_app_tags %}
# {% hello_world %}
# Output: Hello, classy world!