Home > Software engineering >  Jinja2 Python validate var input for rendering a template
Jinja2 Python validate var input for rendering a template

Time:12-22

Hello i try to render a big Template.

The rendering is not a problem, but how can i validate if all defined vars in Template are filled?

for example:

from jinja2 import Template
template_to_render = 'this is a text with are var: {{ var }}'
rendered_template = Template(template_to_render).render({'not_existing_var': 'some_value'})
print(rendered_template)

Output:

this is a text with are var:

The variable var is not used, but removed by jinja from the exmple template.

I have found already some ways to get the vars from jinja2. But using the Jinja2 env will give me only the top level, and the regex solution will not give me deep nested object attributes (the path to the nested field is not visible).

In the end i want to know if a input data dict contain all needed vars for the template. How it is possible to validate the full input?

Edit:

More complicated example to render:

template_to_render = '''
'this is a text with are var: {{ var }}
{% for some_nested_test_value in data.nested_test_value %}
{{ some_nested_test_value }}
{% endfor %}
'''
template_vars = {'var': 'some_value', 'data': {'this_is_invalid': ['a', 'b']}}

CodePudding user response:

You could use Environment() object's method .find_undeclared_variables to get a list of defined variables and then check if all returned variables are in your dictionary used for render

from jinja2 import Template, Environment, meta
env = Environment()
template_to_render = 'this is a text with are var: {{ var }}'
template = env.parse(template_to_render)
missing = meta.find_undeclared_variables(template)

kwargs = {'not_existing_var': 'some_value'}

try:
    if any(req_arg not in kwargs.keys() for req_arg in missing):
        raise NameError(f"variable not filled in template") # gets raised
except NameError as ex:
    print(ex)

kwargs = {'var': 'some_value'}
if any(req_arg not in kwargs.keys() for req_arg in missing):
    raise NameError(f"variable not filled in template")     # does not get raised
  • Related