ld_pvl
ld_pvl

Reputation: 293

Ignore "TemplateAssertionError: no filter named" when doing meta.find_undeclared_variables

I am using jinja2.meta.find_undeclared_variables to find variables used in a template. However, it is failing with TemplateAssertionError when there is an unrecognized filter.

Is there a way to tell jinja2 to ignore these errors and just give back the list of variables?

Upvotes: 0

Views: 1165

Answers (1)

ld_pvl
ld_pvl

Reputation: 293

I ended up writing a small workaround to find all the Name nodes within the parsed template object - below is python 2 code that gives similar result to meta.find_undeclared_variables

def find_variables_in_document(body_list):
    variables = set()
    for body in body_list:
        variables.update(set(find_variables(body)))
    return sorted(variables)


def find_variables(obj):
    if hasattr(obj, '__dict__'):
        if type(obj) is jinja2.nodes.Name:
            yield obj.name
        else:
            for attribute, value in vars(obj).iteritems():
                if isinstance(value, jinja2.nodes.Node):
                    for _ in  find_variables(value):
                        yield _
                if type(value) == list:
                    for item in value:
                        for _ in find_variables(item):
                            yield _

Then the above can be used like this:

from jinja2 import Environment
env = Environment()
ast = env.parse(your_template_string)
print find_variables_in_document(ast.body)

Upvotes: 1

Related Questions