Last Updated: January 23, 2019
·
2.033K
· mnazim

Django: Autoloading tempalate tags the easy way

Raise your right hand, if you hate doing this for every single Django template.

{% load  some_tags  more_tags some_more_tags  %}

This is not DRY. I hate it.

I solve it by adding following at the end of ROOT_URLCONF file:

from django.template.loader import add_to_builtins
add_to_builtins('path.to.some.templatetags.lib')

Now add_to_builtins does not take list or a tupple as argument to autoload multipe tag libs. To remedy that I add a custom setting AUTOLOAD_TEMPLATETAGS to settings.py:

AUTOLOAD_TEMPLATETAGS = (
    'path.to.template.tag1',
    'path.to.template.tag2',
    'path.to.template.tag3',
    ....
)

And then at the end of `ROOT_URLCONF' file:

from django.template.loader import add_to_builtins
for tag in settings.AUTOLOAD_TEMPLATETAGS:
    add_to_builtins(tag)

Voila!

1 Response
Add your response

This is usually not a good practice.I agree we should follow the priniciples of a framework(DRY).Not to mention that any new developer is going to be confuzzled by your use of a tag that doesn't exist in the standard libraries, until they ask you (if you're still around) or stumble upon it. :) Remember, explicit is better than implicit

over 1 year ago ·