Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle NameError and AttributeError gracefully in the Mako runtime environment?

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?

like image 646
David Eyk Avatar asked Sep 09 '11 18:09

David Eyk


1 Answers

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.

like image 104
David Eyk Avatar answered Sep 21 '22 09:09

David Eyk