Skip to content

Instantly share code, notes, and snippets.

@harshithjv
Created May 4, 2023 07:13
Show Gist options
  • Select an option

  • Save harshithjv/2e17950a7cabd3b4be8636dc4359d74f to your computer and use it in GitHub Desktop.

Select an option

Save harshithjv/2e17950a7cabd3b4be8636dc4359d74f to your computer and use it in GitHub Desktop.
Find list of variables from jinja templates
# A small example that works text based templates
# Ref: https://stackoverflow.com/a/8284419
# Note: Works only for top-level variables, i.e., id dictionary is passed then we can't parse keys defined within the dictionaries
from jinja2 import Environment, BaseLoader, meta
if __name__ == '__main__':
template_text = '<div>{{ title }}</div>'
template_env = Environment(loader=BaseLoader())
variable_list = list(meta.find_undeclared_variables(template_env.parse(template_text)))
print("List of variables inside template: "+variable_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment