I am trying to get list of all variables and blocks in a template. I don't want to create my own parser to find variables. I tried using following snippet.
from jinja2 import Environment, PackageLoader env = Environment(loader=PackageLoader('gummi', 'templates')) template = env.get_template('chat.html')
template.blocks
is dict where keys are blocks, how can I get all variables inside the blocks ?
When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.
Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.
Since no one has answered the question and I found the answer
from jinja2 import Environment, PackageLoader, meta env = Environment(loader=PackageLoader('gummi', 'templates')) template_source = env.loader.get_source(env, 'page_content.html') parsed_content = env.parse(template_source) meta.find_undeclared_variables(parsed_content)
This will yield list of undeclared variables since this is not executed at run time, it will yield list of all variables.
Note: This will yield html files which are included using include
and extends
.
I had the same need and I've written a tool called jinja2schema. It provides a heuristic algorithm for inferring types from Jinja2 templates and can also be used for getting a list of all template variables, including nested ones.
Here is a short example of doing that:
>>> import jinja2 >>> import jinja2schema >>> >>> template = ''' ... {{ x }} ... {% for y in ys %} ... {{ y.nested_field_1 }} ... {{ y.nested_field_2 }} ... {% endfor %} ... ''' >>> variables = jinja2schema.infer(template) >>> >>> variables {'x': <scalar>, 'ys': [{'nested_field_1': <scalar>, 'nested_field_2': <scalar>}]} >>> >>> variables.keys() ['x', 'ys'] >>> variables['ys'].item.keys() ['nested_field_2', 'nested_field_1']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With