Skip to content

{{ 'foo' if false }} shortcut not usable with StrictUndefined #710

@ThiefMaster

Description

@ThiefMaster

Using the shortcut version of the ternary operator with no else implies else <undefined>. This is fine when using the normal Undefined but makes this shortcut basically useless with StrictUndefined (and to some extent LoggingUndefined).

>>> from jinja2 import StrictUndefined, Environment
>>> env = Environment(undefined=StrictUndefined)
>>> env.from_string('{{ "foo" if false }}').render()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/adrian/.python-env/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
    return self.environment.handle_exception(exc_info, True)
  File "/home/adrian/.python-env/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "<template>", line 1, in top-level template code
jinja2.exceptions.UndefinedError: the inline if-expression on line 1 evaluated to false and no else section was defined.

I'd change the default from <undefined> to '' - like this the behavior of existing templates will not change (empty output) but it would work fine with the stricter Undefined variants.

The only breakage I could imagine is someone using it in a function/macro call with an explicit is defined check later on. But I think that's rather unlikely and if necessary a new policy option could be added to make it default to <undefined> again.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions