5

我发现尝试访问 Mako 模板中的未定义变量会引发 a NameError,并且在逻辑上是这样。然而,在某些应用程序中,希望更优雅地失败,也许用空字符串替换此类错误(AttributeError是另一个候选者)。这是 Django 模板语言中的默认行为。有没有办法在 Mako 中获得这种行为?

4

1 回答 1

12

好吧,事实证明,再用谷歌搜索一下就明白

import mako.runtime
mako.runtime.UNDEFINED = ''

现在未定义的变量将产生空字符串。

阅读 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

我们开始了。谢谢,谷歌。

于 2011-09-09T23:01:50.613 回答