Django -- How to have a project wide templatetags shared among all my apps in that project

Viewed 15748

Second time asking more details ...

I'd like to have a project wide templagetags directory to have the common tags used by all Apps, then each app can have their own tags if need so.

Let say that I have:

proj1/app1
proj1/app1/templatetags/app1_tags.py

proj1/app2
proj1/app2/templatetags/app2_tags.py

proj1/templatetags/proj1_tags.py

proj1/templates/app1/base.html
proj1/templates/app1/index.html
proj1/templates/app2/base.html
proj1/templates/app2/index.html

Where:

proj1/templates/app1/base.html
-----------
{% load proj1_tags %}
{% load app1_tags %}

proj1/templates/app1/index.html
-----------
{% extends "base.html" %}

proj1/templates/app2/base.html
-----------
{% load proj2_tags %}
{% load app2_tags %}

proj1/templates/app2/index.html
-----------
{% extends "base.html" %}

Would this work? It didn't work for me. It can't find the proj1_tags to load.

5 Answers

I don't know if this is the right way to do it, but in my Django apps, I always place common template tags in a lib "app", like so:

proj/
    __init__.py
    lib/
        __init__.py
        templatetags/
            __init__.py
            common_tags.py

Just make sure to add the lib app to your list of INSTALLED_APPS in settings.py.

Django registers templatetags globally for each app in INSTALLED_APPS (and that's why your solution does not work: project is not an application as understood by Django) — they are available in all templates (providing they was properly registered).

I usually have an app that handles miscellaneous functionality (like site's start page) and put templatetags not related to any particular app there, but this is purely cosmetic.

This is the place where you place it in settings.py.

The first key('custom_tags' in this case) in 'libraries' should be what you want to load name in template.


PROJECT STRUCTURE

mysite
    - myapp
    - mysite
        - manage.py
        - templatetags
            - custom_tags.py

SETTINGS.PY

TEMPLATES = [
    {
        'BACKEND': '....',
        'OPTIONS': {
            'context_processors': [
                ...
            ],
            'libraries': {
                'custom_tags': 'mysite.templatetags.custom_tags',
            }
        },
    },
]
Related