Django: a canconical method for a package to offer new template tags?

Question:

I’m building a package of Django extensions and one thing I’d like to include in it now are template tags (and filters). The question is, how does a package provide template tags to a Django project?

The context is of an installed package. Say I have written a packaged called mypackage and I install it with pip, and it ends up in say:

/home/me/.local/lib/python3.8/site-packages/mypackage

(pip can install packages in numerous different places including local, system, venvs and such this is just an example).

I imagine in a Django app, in the templatetags directory adding a line to two to access them. Something like:

from mypackage.template import tags

say. Or if need actually running something to register them, possibly as built-in tags a la:

https://djangosnippets.org/snippets/342/

from mypackage.template import register_tags

register_tags()

Before I experiment this to death (given I can’t find any docs or example yet) I’m curious if there’s a canonical approach to this as there are many Django extension packages. To be honest if I could reliably find one that provides template tags it could serve as an example of course.

Any tips in this regard are appreciated.

Asked By: Bernd Wechner

||

Answers:

Given some gracious tips in the comments, I invested a little time into some experiments and can confirm it is very very simple indeed to do what I had hoped for. Here is all that is required:

  1. The package must have a templatetags folder. In the cited example that would be:
    • /home/me/.local/lib/python3.8/site-packages/mypackage/templatetags
  2. That folder must have a file registering the tags, in the cited example possibly:
    • /home/me/.local/lib/python3.8/site-packages/mypackage/templatetags/newtags.py
  3. The package must be included as an app in settings.py for example:
    • INSTALLED_APPS = ('mypackage', ...
  4. Its tags can now be loaded in any template by referencing the file that registers the templates, in the cited example:
    • {% load newtags %}

It is that simple for any package to provide tags, the catches to be aware of that I don’t find well documented are:

  1. The name of the file that registers the tags (newtags.py in the cited instance) must be unique (not clash with a name in the app loading these tags). It seems to land in one namespace with the name newtags in this case and if that’s already in the namespace one or the other wins out (not sure which as haven’t tested that extensively).
  2. There are no further configs needed, the package does not need an app config at all, and there are no further demands Django imposes upon us (as at version 3), we really do, only need to add the package to INSTALLED_APPS and give it a templatetags directory in which we place a file registering our tags, it really is, that simple.
Answered By: Bernd Wechner