我试图在使用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
Run Code Online (Sandbox Code Playgroud)
所以我可以在另一个模板中使用它:
{% if 'profile/header.html'|template_exists %}
{% include 'profile/header.html' %}
{% else %}
{% include 'common/header.html' %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我可以避免使用诸如在INSTALLED_APPS中更改我的应用程序的顺序等解决方案.
但是,它不起作用.如果模板不存在,那么异常会在堆栈/控制台中引发,但它不会传播到get_template(..)(从此语句中),因此不会传播给我愚蠢的 API.因此,在渲染过程中,这会在我的脸上爆炸.我将stacktrace上传到了pastebin
这是Django的通缉行为吗?
我最终停止做愚蠢的事情.但我的问题仍然存在.
自定义标签怎么样?这不提供完整的功能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)
Run Code Online (Sandbox Code Playgroud)
然后在你的模板中:
{% include_fallback "profile/header.html" "common/header.html" %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1553 次 |
| 最近记录: |