Jinja2 find_undeclared_variables ignores globals?

1.1k views Asked by At

I want to find out which variables of a Jinja2 template are not covered by globals. I load the template source, parse it and feed the result into meta.find_undeclared_variables. No matter what is in the global dictionary of the environment I get a full list of variables for the template. How do I make this operation recognize the globals in the environment and in the template and only return the list of variables not covered by them.

The sample below creates an environment, renders the template to show that global variables are indeed read and calls meta.find_undeclared_variables to show its result.

from jinja2 import Environment, meta, FunctionLoader, PrefixLoader

def load_mapping(name):
    return 'Mapping %s {{version}} {{docid}}' % name

def load_link(name):
    return 'Link %s {{version}} {{docid}}' % name

loader = PrefixLoader({
    'link': FunctionLoader(load_link),
    'map':  FunctionLoader(load_mapping)
})

env = Environment(loader=loader)

globals = {'version': '1.0'}
env.globals.update(globals)

print env.get_template('map/test').render(docid='asdf')

tsrc = env.loader.get_source(env, 'link/test')
parsed = env.parse(tsrc)
print meta.find_undeclared_variables(parsed)

The code prints:

Mapping test 1.0 asdf
set(['version', 'docid'])

With version being a global I would like to change my code so that only docid is returned.

I use Python 2.7.6 and Jinja 2.7.3.

1

There are 1 answers

2
voscausa On
jinja_globals = env.globals.keys()
print meta.find_undeclared_variables(parsed) - set(jinja_globals)