Skip to main content

Undefined Variables

When rendering a Liquid template, if a variable name can not be resolved, an instance of liquid.Undefined is used instead. We can customize template rendering behavior by implementing some of Python's "magic" methods on a subclass of liquid.Undefined.

Default Undefined

All operations on the default Undefined type are silently ignored and, when rendered, it produces an empty string. For example, you can access properties and iterate an undefined variable without error.

Hello {{ nosuchthing }}
{% for thing in nosuchthing %}
{{ thing }}
{% endfor %}

Strict Undefined

When liquid.StrictUndefined is passed as the undefined argument to Environment or Template, any operation on an undefined variable will raise an UndefinedError.

from liquid import Environment, StrictUndefined

env = Environment(undefined=StrictUndefined)
template = env.from_string("Hello {{ nosuchthing }}")
# UndefinedError: 'nosuchthing' is undefined, on line 1

The default filter

With StrictUndefined, the built-in default filter does not handle undefined variables the way you might expect. The following example will raise an UndefinedError if username is undefined.

Hello {{ username | default: "user" }}

New in version 1.4.0

We can use the built-in StrictDefaultUndefined type, which plays nicely with the default filter, while still providing strictness elsewhere.

from liquid import Environment
from liquid import StrictDefaultUndefined

env = Environment(undefined=StrictDefaultUndefined)
template = env.from_string('Hello {{ username | default: "user" }}')
Hello user

Falsy StrictUndefined

It's usually not possible to detect undefined variables in a template using an if tag. In Python Liquid we can implement an Undefined type that allows us to write {% if nosuchthing %}, but still get some strictness when undefined variables are used elsewhere.

from liquid import Environment
from liquid import StrictUndefined

class FalsyStrictUndefined(StrictUndefined):
def __bool__(self) -> bool:
return False

def __eq__(self, other: object) -> bool:
if other is False:
return True
raise UndefinedError(self.msg)

env = Environment(undefined=FalsyStrictUndefined)

template = env.from_string("{% if nosuchthing %}foo{% else %}bar{% endif %}")
template.render() # "bar"

template = env.from_string("{{ nosuchthing }}")
# UndefinedError: 'nosuchthing' is undefined, on line 1