Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django custom template tags and template loaders

[I have this discussion at http://groups.google.com/group/django-users/browse_thread/thread/989c569d5118980d]

Is 'django.template.loaders.app_directories.load_template_source' required in the TEMPLATE_LOADERS setting for custom template tags to work?

We know that simply having a custom tag in the templatetags directory of your Django application makes that tag available for use in the application.

In the case of loading of templates, we know that having 'django.template.loaders.filesystem.load_template_source' in the TEMPLATE_LOADERS setting together with appropriate entries in TEMPLATE_DIRS enables Django to load templates from the specified directories. This is pretty clear and logical. But in the case of custom template tags, I see them becoming magically available.

So do you have any idea how custom template tags are found/loaded/handled?

like image 589
chefsmart Avatar asked Dec 30 '22 18:12

chefsmart


1 Answers

No, django.template.loaders.app_directories.load_template_source is not at all required for custom template tags to work.

You do not have to specify directories to tell django where-from to load templatetags libraries (as we do in case of templates), just coz django assumes to find templatetags libraries in applications specified in INSTALLED_APPS list.

It just loops over the application list of INSTALLED_APPS, importing all libraries from 'templatetags' directories within, and import each to make them available. If a directory called templatetags isn't found, it just skips. But, it does try to look at all available options in INSTALLED_APPS.

You can have a look at code in django/templatetags/__init__.py, and you will know how templatetags made (magically) available. Look at the code,

from django.conf import settings

for a in settings.INSTALLED_APPS:
    try:
        __path__.extend(__import__(a + '.templatetags', {}, {}, ['']).__path__)
    except ImportError:
        pass

It just add those module list to __path__. And anything listed to __path__ will, be treated as if it also exists as a sub-module of the module whose __path__ list it appears in.

like image 176
simplyharsh Avatar answered Jan 15 '23 11:01

simplyharsh