Django自定义模板标签和模板加载器

che*_*art 4 django django-templates

[我在http://groups.google.com/group/django-users/browse_thread/thread/989c569d5118980d进行了此次讨论]

TEMPLATE_LOADERS设置中是否需要'django.template.loaders.app_directories.load_template_source'才能使用自定义模板标签?

我们知道,只需在Django应用程序的templatetags目录中使用自定义标记,就可以在应用程序中使用该标记.

在模板负荷的情况下,我们知道有在TEMPLATE_LOADERS设置"django.template.loaders.filesystem.load_template_source" 一起在TEMPLATE_DIRS相应条目使Django的从指定目录中加载模板.这非常清楚和合乎逻辑.但在自定义模板标签的情况下,我看到它们变得神奇可用.

那么你知道如何找到/加载/处理自定义模板标签吗?

sim*_*rsh 10

不,django.template.loaders.app_directories.load_template_source自定义模板标签无需工作.

您不必指定目录来告诉django where-from加载templatetags库(就像模板一样),只是coz django假定在INSTALLED_APPSlist 中指定的应用程序中找到templatetags库.

它只是遍历应用程序列表INSTALLED_APPS,从" templatetags "目录中导入所有库,并导入每个库以使它们可用.如果找不到名为templatetags的目录,它只会跳过.但是,它确实试图查看INSTALLED_APPS中的所有可用选项.

您可以查看代码django/templatetags/__init__.py,并了解模板标签的制作方式(神奇地).看看代码,

from django.conf import settings

for a in settings.INSTALLED_APPS:
    try:
        __path__.extend(__import__(a + '.templatetags', {}, {}, ['']).__path__)
    except ImportError:
        pass
Run Code Online (Sandbox Code Playgroud)

它只是将那些模块列表添加到__path__.列出的任何内容都__path__将被视为它作为模块的子模块存在,该模块的__path__列表出现在其中.