Skip to content
Advertisement

how to get list of all variables in jinja 2 template file

I have a usecase where I want to get a list of unreferenced variables in a jinja2 template. I found some explanations on stackoverflow on how to do this, but not of these exaples use a file as a template, and I am very, very stuck

Here is my code. Lines 8 and 9 can be omitted, ofc.

import jinja2
from jinja2 import meta


env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="./"))
template_file = "testfile.txt"
template = env.get_template(template_file)
data = dict(foo='foo', bar='bar')
print(template.render(data))


data = dict(foo='foo')
test = env.parse(data, template)
print(meta.find_undeclared_variables(test))

here is the content of ‘testfile.txt’

this should print foo:{{foo}}
this should print bar:{{bar}}

here’s my output

this should print foo:foo
this should print bar:bar

set()

What I would like to get as output is the string ‘bar’ in the set like below, as ‘bar’ is not referenced in the ‘data’ dict.

this should print foo:foo
this should print bar:bar

set('bar')

any help solving this would be greatly appreciated

Advertisement

Answer

First I want to make a clarification, jinja considers variables to be those that are assigned through the instance attribute global of Environment class. The global attribute is a dictionary that contains the variables that we are going to use in our template.

import jinja2
from jinja2 import meta


env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath="./"))

# Declare foo, but no bar
env.globals['foo'] = 'foo'

# Load the template as a file and read it
with open("testfile.txt") as file:
    ast = env.parse(file.read())

# Find the undeclared variables of our template loaded with an environment that
# only has 'foo' declared in it `globals` attr.
undeclared_variables = meta.find_undeclared_variables(ast)

print(undeclared_variables)

Result:

{'bar'}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement