【问题标题】:Django-templates: share custom inclusion tag between appsDjango-templates:在应用程序之间共享自定义包含标签
【发布时间】:2015-01-07 16:25:18
【问题描述】:

关于查找模板有很多问题,但我找不到与自定义标签相关的任何内容。

我有以下示意图项目结构: / |- app1 | |- templatetags | | |- my_helpers.py | |- templates | |- my_helpers | |- my_tag.html |- app2 |- templates |- include | |- inclusion.html |- base.html

my_helpers.py 中定义了一个简单的包含标记:

from django import template
register = template.Library()    
@register.inclusion_tag('my_helpers/my_tag.html')
def my_tag(...):
    ...

app2/templates/base.html 看起来像这样:

{% load my_helpers %}
... some markup ...
{% my_tag %}
{% include 'include/inclusion.html' %}

这里my_tag 工作得很好。但是,当我尝试在 'include/inclusion.html' 中使用它时(我在其中添加了一个 {% load my_helpers %} 标记),它失败了:

django.template.base.TemplateDoesNotExist
TemplateDoesNotExist: my_helpers/my_tag.html

据我了解,它仅在当前应用程序中查找模板。但是为什么它只发生在included 模板上呢?有没有可能让它发挥作用?

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    要实现这一点,您可以利用 Django 模板加载器的功能。 您可以创建您的项目结构,如下所示 - |- templates | |- common_templates | |- my_tag.html |- app1 | |- templatetags | | |- my_helpers.py | |- templates | |- my_helpers | |- app2 |- templates |- include | |- inclusion.html |- base.html

    你的 my_helpers.py 可以像

    from django import template
    register = template.Library()    
    @register.inclusion_tag('common_templates/my_tag.html')
    def my_tag(...):
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 2012-12-22
      • 2017-02-01
      • 2012-06-02
      相关资源
      最近更新 更多