π·οΈ Template Tags & FiltersΒΆ
Duck allows you to extend templates using template tags and filters, supporting both Jinja2 and Django template engines.
This gives you the flexibility to write reusable logic directly in templates π.
π Syntax OverviewΒΆ
Default Template TagΒΆ
Django:
{% sometag 'inputs' %}βinputsare the arguments.Jinja2:
{{ sometag('inputs') }}βinputsare the arguments.
Block Template TagΒΆ
Django:
{% sometag %} Some data {% endsometag %}Jinja2:
{% sometag %} Some data {% endsometag %}
Template FilterΒΆ
Django:
{{ somevalue | somefilter }}Jinja2:
{{ somevalue | somefilter }}
π·οΈ Quick CheatsheetΒΆ
Feature |
Django Syntax |
Jinja2 Syntax |
|---|---|---|
Default Template Tag |
|
|
Block Template Tag |
|
|
Template Filter |
`{{ value |
filter }}` |
π¨βπ» Example UsageΒΆ
# templatetags.py
from duck.template.templatetags import TemplateTag, TemplateFilter, BlockTemplateTag
# Define a regular template tag
def mytag(arg1, context):
# Custom logic here
return "some data"
# Define a template filter
def myfilter(data):
# Process data
return data
# Define a block template tag
def myblocktag(content):
# Process block content
return content
# Register your tags and filters
TEMPLATETAGS = [
TemplateTag("name_here", mytag, takes_context=True), # takes_context defaults to False
TemplateFilter("name_here", myfilter),
BlockTemplateTag("name_here", myblocktag)
]
β‘ NotesΒΆ
For Django templates rendered via
django.shortcuts.render, insert this at the top of your template:
{% load ducktags %}
This is only required if the Django project is integrated into Duck.
If using Duckβs internal
renderfunctions or classes likeTemplateResponse, no extra loading is needed.Use this primarily for standalone Django templates unrelated to Duckβs template system.
β¨ With Duck template tags & filters, you can write cleaner templates, reuse logic, and mix powerful Python code into templates effortlessly π·οΈ