【发布时间】:2013-01-23 13:43:32
【问题描述】:
我正在尝试在使用 Django 1.4.3(使用 Python 2.7.2)的项目中使用 SO answer:https://stackoverflow.com/a/6217194/493211 中描述的模板标签。
我是这样改编的:
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
这样我就可以在另一个模板中像这样使用它:
{% if 'profile/header.html'|template_exists %}
{% include 'profile/header.html' %}
{% else %}
{% include 'common/header.html' %}
{% endif %}
这样,我本可以避免使用诸如在 INSTALLED_APPS 中更改应用顺序等解决方案。
但是,它不起作用。如果模板不存在,则在堆栈/控制台中引发异常,但它不会传播到get_template(..)(来自此statement),因此不会传播到我的愚蠢的 API。因此,在渲染过程中,这在我的脸上爆炸了。我将stacktrace上传到pastebin
这是 Django 想要的行为吗?
我最终不再照原样做愚蠢的事情。但我的问题仍然存在。
【问题讨论】:
-
当你试图捕捉
template.loader.TemplateDoesNotExist时会发生什么? -
感谢参与。我得到了相同的堆栈
-
我发布了一个实际上是一种解决方法的答案,我不介意“真实”的解释。