5

I've found that trying to access an undefined variable within a Mako template raises a NameError, and quite logically so. In some applications, however, it's desirable to fail more gracefully, perhaps substituting the empty string on such errors (AttributeError is another candidate). This is the default behavior in the Django template language. Is there a way to get this behavior in Mako?

David Eyk
  • 12,171
  • 11
  • 63
  • 103

1 Answers1

12

Well, turns out that a little more googling makes it plain:

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

Now undefined variables will produce the empty string.

Reading the source for the original value of UNDEFINED is enlightening:

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

And there we go. Thanks, Google.

David Eyk
  • 12,171
  • 11
  • 63
  • 103
  • To be fair, my attempts at Googling this problem were futile as well. Thanks anyway. – Ross Apr 17 '12 at 18:10