检查Django模板中是否存在模板 [英] Check if a template exists within a Django template

查看:350
本文介绍了检查Django模板中是否存在模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将Django模板包含在Django模板中之前,是否有一个开箱即用的方式来检查模板是否存在?替代方案也是受欢迎的,但由于特定情况,其中一些将不起作用。

Is there an out-of-the-box way of checking if a template exists before including it in a Django template? Alternatives are welcome too but some of them would not work due to the particular circumstances.

例如,这里有一个略有不同的问题的答案。这不是我要找的:
如何检查Django中是否存在模板?

For example, here's an answer to a slightly different question. This is not what I'm looking for: How to check if a template exists in Django?

推荐答案

假设包含如果你传递一个坏的模板引用不会炸毁,那可能是最好的方法。另一种选择是创建一个模板标签,它基本上是在你提到的链接中进行检查。

Assuming include doesn't blow up if you pass it a bad template reference, that's probably the best way to go. Your other alternative would be to create a template tag that essentially does the checks in the link you mentioned.

非常基本的实现:

from django import template

register = template.Library()

@register.simple_tag
def template_exists(template_name):
    try:
        django.template.loader.get_template(template_name)
        return "Template exists"
    except template.TemplateDoesNotExist:
        return "Template doesn't exist"

在您的模板中:

{% template_exists 'someapp/sometemplate.html' %}

那个标签并不是那么有用,所以你可能想要创建一个实际上添加一个变量到上下文中的变量,然后你可以检查一个if语句或者什么不是。

That tag isn't really all that useful, so you'd probably want to create one that actually adds a variable to the context, which you could then check in an if statement or what not.

这篇关于检查Django模板中是否存在模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆