在江抓模板不是专家

2024-05-20 22:58:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在使用django1.4.3(python2.7.2)的项目中使用SO answer:https://stackoverflow.com/a/6217194/493211中描述的templatetag。在

我是这样改编的:

from django import template


register = template.Library()

@register.filter
def template_exists(template_name):
    try:
        template.loader.get_template(template_name)
        return True
    except template.TemplateDoesNotExist:
        return False

这样我就可以在另一个模板中使用它:

^{pr2}$

这样,我就可以避免使用诸如更改已安装应用程序中应用程序顺序的解决方案。在

但是,它不起作用。如果模板不存在,则在堆栈/控制台中引发异常,但它不会传播到get_template(..)(从这个statement内部),因此不会传播到我的愚蠢的API。因此,在渲染过程中,这会在我的脸上爆炸。我把stacktrace上传到pastebin

这是Django通缉的行为吗?在

我最终不再做愚蠢的事了。但我的问题仍然存在。在


Tags: 项目answernamefromhttpscomregister模板
2条回答

我找到了我问题的答案,所以我把它贴在这里以备将来参考。在

如果我使用我的模板,你存在这样的过滤器

{% if 'profile/header.html'|template_exists %}        
  {% include 'profile/header.html' %}
{% else %}
  {% include 'common/header.html' %}
{% endif %}

如果profile/header.html不存在,那么templatedoesnotextist会在页面加载时奇怪地传播,我会得到一个服务器错误。但是,如果我在模板中使用以下内容:

^{pr2}$

那么,它就像一个符咒!在

显然,我可以用

django.template.loader.select_template(['profile/header.html','common/header.html']) 

在视图中(从这个SO answer)。但我使用的是一个CBV,我想保持相当通用,这是从主模板调用的。我还认为,如果这个应用程序因为任何原因宕机了,我的网站也能正常工作。如果你觉得这很傻,请留下评论(或者更好的答案)。在

定制标签呢?这并没有提供include的全部功能,但似乎满足了问题中的需求:

@register.simple_tag(takes_context=True)
def include_fallback(context, *template_choices):
    t = django.template.loader.select_template(template_choices)
    return t.render(context)

然后在模板中:

^{pr2}$

相关问题 更多 >