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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With