how can i get all required variables and attributes in a jinja2 templates to render

Question:

I am trying to build a configuration generator for myself using jinja2. I need to know what are the expected variables and their keys before trying to render template to provide a sample file to fill before template rendering. Required parameters will change based on selected configuration type and used templates. I don’t want to store all required parameters because templates will be changed time to time and also new templates will be added. There will be 50ish parameter per template

here is a sample template file

{{data.config1[0].field1}}
{{data.config2[0].field3}}
firt level change test
{% for row in data.config1 %}
{% if row.field3=='1' %}
something {{row.field1}} {{row.field2}}
{% else %}
something {{row.field1}}
{% endif %}
{% endfor %}
footer thingy
{{data.config2[0].field5}}

i tried to use find_undeclared_variables from jinja2.meta package
here is my sample code

import os
from jinja2 import Environment, FileSystemLoader,meta

template_filename = 'change.txt'
PATH = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_ENVIRONMENT = Environment(
                autoescape=False,
                loader=FileSystemLoader(os.path.join(PATH)),
                trim_blocks=False)
template_source =TEMPLATE_ENVIRONMENT.loader.get_source(TEMPLATE_ENVIRONMENT,   template_filename)[0]
parsed_content = TEMPLATE_ENVIRONMENT.parse(template_source)
variables= meta.find_undeclared_variables(parsed_content)
print (variables)

this is what i can get

{'data'}

my desired output something like this.

{'config1':['field1','field2','field3'], 'config2':['field3','field5']}

please suggest.

Asked By: moth

||

Answers:

I have used, Jinja2schema to generate expexted output.

Answered By: moth

There exists the
jinja2.meta.find_undeclared_variables function that may help you:

https://jinja.palletsprojects.com/en/3.1.x/api/#jinja2.meta.find_undeclared_variables

Answered By: Brian Ritz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.