python / beginner
Snippet
Custom Simple Template Tags
Simple tags are Python functions that return a string or value to be displayed directly in your HTML templates.
snippet.py
1
2
3
4
5
6
7
8
from django import templateimport datetimeregister = template.Library()@register.simple_tagdef current_year():return datetime.datetime.now().year
django
Breakdown
1
register = template.Library()
An instance used to register your custom tags with the template engine.
2
@register.simple_tag
A decorator that tells Django this function is a template tag.
3
return datetime.datetime.now().year
The value returned here is what will be rendered in the template.