max
max

Reputation: 10454

how to get nested undeclared variables in python jinja2

I have an xml template and I'm loadind data into it using jinja2 template engine. I'm trying to validate that all the variables in the template are supplied:

from jinja2 import Environment, PackageLoader, meta
tmp = JinjaEnvironment().from_string(TEMPLATE)
parsed_content = tmp.environment.parse(TEMPLATE)
for key in meta.find_undeclared_variables(parsed_content):
    if key not in data:
        print 'Missing ', key

The problem is that the find_undeclared_variables method does not return nested variables.

For example if my data is {'main': {'age': 22, 'height': 6}, 'size': 10}
then that method returns ['main', 'size']
but what I need is ['main.age', 'main'height', 'size']

The goal is to validate that all variable are substituted. Any ideas?

Upvotes: 1

Views: 829

Answers (1)

max
max

Reputation: 10454

I found the package that helps with that: jinja2schema

from jinja2schema import infer, model
def test(self):
    for key, val in infer(TEMPLATE).items():
        assert key in self.data, 'Missing {}'.format(key)

        if type(val) == model.List:
            for subkey in val.item.keys():
                assert subkey in self.data[key][0], 'Missing {}.{}'.format(key, subkey)

        elif type(val) == model.Dictionary:
            for subkey in val.keys():
                assert subkey in self.data[key], 'Missing {}.{}'.format(key, subkey)

Upvotes: 1

Related Questions