Correctly handle variable issues when evaluating jinja2 when statements

Fixes #4025