Gilang Chandrasa Thoughts, stories, and ideas

Autoload custom template tags in Django

While it’s not always good practice (non-portable to any other project), but there is time when your project need to do this, having custom template tags autoload so it can be accessed in all your templates without {% raw %}{% load ... %}{% endraw %}

Most of my templates is unique to the project anyway, so let’s do this.

Django < 1.7

You can put these lines at the end of your main urls.py

from django.template.loader import add_to_builtins

add_to_builtins('yourapp.templatetags.custom_tags')

Django 1.7 - 1.8

urls.py

from django.template.base import add_to_builtins

add_to_builtins('yourapp.templatetags.custom_tags')

Django 1.9

settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'builtins': ['myapp.builtins'],
        },
    },
]