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

55👍

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.

👤mipadi

35👍

Since Django 1.9, it is no longer necessary to create additional common app as others mentioned. All you need to do is to add a path to your project templatetags directory to the settings.py‘s OPTION['libraries'] dict.

After that, these tags will be accessible throughout your whole project. The templatetags folder can be placed wherever you need and can also have different name.

Customized example from the Django docs:

OPTIONS={
    'libraries': {
        'myapp_tags': 'path.to.myapp.tags',
        'project_tags': 'project.templatetags.common_extras',
        'admin.urls': 'django.contrib.admin.templatetags.admin_urls',
    },
}

7👍

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.

👤zgoda

6👍

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',
            }
        },
    },
]
👤Tony

-2👍

Django works by App. They are refer in the INSTALLED_APPS setting.

I suggest to you to split everything related to a different app. For your templatetags problem, you could create an app called ‘common_tags’. Then setup the INSTALLED_APPS settings to use it, and you’ll be able to load your common tags from any templates like so:

{% load XXXX %}
👤FlogFR

Leave a comment