我发现尝试访问 Mako 模板中 undefined variable 会引发 NameError
,这在逻辑上是正确的。然而,在某些应用程序中,希望更优雅地失败,也许在此类错误上替换为空字符串(AttributeError
是另一个候选者)。这是 Django 模板语言的默认行为。有没有办法在 Mako 中获得这种行为?
最佳答案
好吧,结果是多一点谷歌搜索 makes it plain :
import mako.runtime
mako.runtime.UNDEFINED = ''
现在 undefined variable 将产生空字符串。
阅读 UNDEFINED 原始值的来源很有启发性:
class Undefined(object):
"""Represents an undefined value in a template.
All template modules have a constant value
``UNDEFINED`` present which is an instance of this
object.
"""
def __str__(self):
raise NameError("Undefined")
def __nonzero__(self):
return False
我们开始了。谢谢,谷歌。
关于python - 如何在 Mako 运行环境中优雅地处理 NameError 和 AttributeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7365848/