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

风格不统一 提交于 2019-12-03 03:37:56

问题


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.


回答1:


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.




回答2:


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',
    },
}



回答3:


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.




回答4:


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 %}


来源:https://stackoverflow.com/questions/890942/django-how-to-have-a-project-wide-templatetags-shared-among-all-my-apps-in-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!