如果在上下文中缺少变量,如何使Django模板引发错误 [英] How to make Django template raise an error if a variable is missing in context
问题描述
我在非Django项目中使用Django模板,我想确保我的模板不包含不在上下文中的变量的引用,因为我需要Django模板渲染器来引发错误,当它看到 {{non_existent_variable}}
当上下文中没有 non_existent_variable
I'm using Django templates in a non-Django project and I want to make sure that my templates contain no references to variables that are not in context and for that I need Django template renderer to raise an error when it sees {{ non_existent_variable }}
when there is no non_existent_variable
in Context.
TEMPLATE_STRING_IF_INVALID
可以设置为某些东西,然后我们可以检查这个东西不在渲染的模板中,但这根本不是优雅的。
TEMPLATE_STRING_IF_INVALID
could be set to something and then we could check that this something is not in the rendered template, but that is not elegant at all.
我可以以某种方式没有太多的工作重写方式Context吞没缺少的关键错误?
Can I somehow without too much work override the way Context swallows missing key errors?
推荐答案
有一个 Django Snippet ,它提供了一个解决方案:
There is a Django Snippet which provides a solution:
# 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模板引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!