[Python] Jinja2 Python validate var input for rendering a template

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    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']}}

    Continue reading...

Compartilhe esta Página