pythonjinja2

Make all if statements true in Jinja2 templates


I am writing a Jinja2 template validator where I want to check all possibly needed variables. I already implemented my own Undefined class and can successfully detect missing variables, but obviously variables within if-statements are not found.

I do not want to hardcode multiple if-else-cases, so I am wondering if there is a way to make all if-statements true so that I do not check the "else" cases only.

Maybe a way to temporary overwrite the jinja2 function for the {% if %} or something?

Here's my code that detects the used variables:

def find_all_variables(template_path):
    variables, undefined_cls = create_collector()

try:
    env = Environment(loader = FileSystemLoader(searchpath="./"), autoescape = select_autoescape(),undefined=undefined_cls)
    template = env.get_template(template_path)
    print(template.render({})) # empty so all variables are undefined
except TemplateError as error:
    print(f"Validation of script {template_path} failed:")
    print(error)
    exit(1)

return variables

Solution

  • I found the answer myself from a different question. The solution is to use build-in jinja2 function meta.find_undeclared_variables() on the parsed template.

    This checks the whole template regardless of any if-statements or other control functions. Example is provided here: https://stackoverflow.com/a/8284419/2721265