为“templatetags”使用自定义目录

Col*_*isa 7 django django-1.7

有人知道它是否可能对“templatetags”使用自定义目录eje:“my-project/templatetags”

Normal
My-Project-Name
  My-App
    __init__.py
      templatetags
        __init__.py
Run Code Online (Sandbox Code Playgroud)

需要一些这样的

My-Project-Name
  templatetags
    __init__.py
Run Code Online (Sandbox Code Playgroud)

rai*_*n01 8

这个有可能。只需添加您的位置templatetags.py或templatetags目录的Djangosettings.pyOPTIONS模板中设置。

在我的情况下,我将我的模板标签放在libs/位于项目根目录的目录中。
您有两个选择,builtins或者libraries

TEMPLATES = [{
    ...
    'OPTIONS': {
        ...
        'builtins': [
            'libs.templatetags'
        ],
        # or as @x-yuri pointed out, you can put them in `libraries`
        'libraries': {
            'my_tags': 'libs.templatetags',
        },
    }
}]
Run Code Online (Sandbox Code Playgroud)

如果您使用builtins,它随处可用,您不需要为此使用{% load %}
如果您使用libraries,则需要使用{% load my_tags %}.

  • 还有 [`libraries`](https://docs.djangoproject.com/en/2.2/topics/templates/#module-django.template.backends.django) 选项供按需加载。 (3认同)

kar*_*ikr 2

这不可能。原因是,templatetags 必须驻留在 django 应用程序内。

\n\n

来自以下文档templatetags

\n\n
\n

自定义模板标签和过滤器必须位于 Django 应用程序内。如果它们与现有应用程序相关,则将它们捆绑在那里是有意义的;否则,您应该创建一个新应用程序来保存它们。

\n\n

应用程序应包含一个 templatetags 目录,与 models.py、views.py 等处于同一级别。如果该目录不存在,请创建它 - 不要忘记文件__init__.py以确保目录被视为 Python 包。添加此模块后,您需要重新启动服务器,然后才能使用模板中的标签或过滤器。

\n
\n