python – 在Django中捕获TemplateDoesNotExist
发布时间:2020-12-16 21:41:32 所属栏目:Python 来源:网络整理
导读:我试图在使用Django 1.4.3(使用 Python 2.7.2)的项目中使用SO答案: https://stackoverflow.com/a/6217194/493211中描述的模板标签. 我这样改编: from django import templateregister = template.Library()@register.filterdef template_exists(template_n
我试图在使用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的通缉行为吗? 我最终停止做愚蠢的事情.但我的问题仍然存在. 解决方法
自定义标签怎么样?这并没有提供包含的全部功能,但似乎满足了问题中的需求:
@register.simple_tag(takes_context=True) def include_fallback(context,*template_choices): t = django.template.loader.select_template(template_choices) return t.render(context) 然后在你的模板中: {% include_fallback "profile/header.html" "common/header.html" %} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |