jinja2.Environment.compile_expression

Environment.compile_expression(source, undefined_to_none=True)[source]

A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression.

This is useful if applications want to use the same rules as Jinja in template “configuration files” or similar situations.

Example usage:

>>> env = Environment()
>>> expr = env.compile_expression('foo == 42')
>>> expr(foo=23)
False
>>> expr(foo=42)
True

Per default the return value is converted to None if the expression returns an undefined value. This can be changed by setting undefined_to_none to False.

>>> env.compile_expression('var')() is None
True
>>> env.compile_expression('var', undefined_to_none=False)()
Undefined

New in version 2.1.