我试图在使用Django 1.4.3(使用
Python 2.7.2)的项目中使用SO答案:
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的通缉行为吗?
我最终停止做愚蠢的事情.但我的问题仍然存在.