在 django 模板中,如果未定义,调用{{ var }}
将静默失败。var
这使得模板难以调试。有没有我可以切换的设置,所以 django 在这种情况下会抛出异常?
我在网上找到的解决方案的唯一提示是http://groups.google.com/group/google-appengine/browse_thread/thread/86a5b12ff868038d,这听起来非常骇人听闻。
在 django 模板中,如果未定义,调用{{ var }}
将静默失败。var
这使得模板难以调试。有没有我可以切换的设置,所以 django 在这种情况下会抛出异常?
我在网上找到的解决方案的唯一提示是http://groups.google.com/group/google-appengine/browse_thread/thread/86a5b12ff868038d,这听起来非常骇人听闻。
姜戈<=1.9
设置TEMPLATE_STRING_IF_INVALID = 'DEBUG WARNING: undefined template variable [%s] not found'
在您的settings.py
.
请参阅文档:
https ://docs.djangoproject.com/en/1.9/ref/settings/#template-string-if-invalid
姜戈>=1.10
在string_if_invalid = 'DEBUG WARNING: undefined template variable [%s] not found'
您的settings.py
.
请参阅文档:https ://docs.djangoproject.com/en/2.0/topics/templates/#module-django.template.backends.django
另请阅读: http ://docs.djangoproject.com/en/dev/ref/templates/api/#invalid-template-variables
当模板中遇到未定义的变量时,来自djangosnippets的这个 hack将引发异常。
# settings.py
class InvalidVarException(object):
def __mod__(self, missing):
try:
missing_str = unicode(missing)
except:
missing_str = 'Failed to create string representation'
raise Exception('Unknown template variable %r %s' % (missing, missing_str))
def __contains__(self, search):
if search == '%s':
return True
return False
TEMPLATE_DEBUG = True
TEMPLATE_STRING_IF_INVALID = InvalidVarException()
考虑使用 django-shouty-templates 应用程序:https ://pypi.org/project/django-shouty-templates/
这个应用程序应用了一个猴子补丁,它强制 Django 的模板语言在无效假设方面发出更大的错误。具体来说:
chef
如果调用变量会引发异常sous_chef
。chef.can_add_cakes
can_add_cakes
如果不是厨师的有效属性/属性/方法,将引发异常这不是编译时安全,但总比因为忘记了什么而默默吞下错误要好!
这是设计的一部分。它允许您提供默认值并根据上下文中是否存在变量进行切换。它还允许模板非常灵活并促进模板的可重用性,而不是严格的“每个视图必须有自己的模板”方法。
更重要的是,模板实际上不应该被“调试”。这个想法是将尽可能多的逻辑放在模板之外,在视图或模型中。如果您想弄清楚为什么不应该传递给上下文的变量,那么调试的地方就在您的视图中。在您的视图返回之前放在import pdb;pdb.set_trace()
某个地方并四处寻找。