Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of all variables in jinja 2 templates

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 ?

like image 351
Kracekumar Avatar asked Nov 24 '11 17:11

Kracekumar


People also ask

What is Autoescape in Jinja2?

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.

What is Jinja2 syntax?

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.


2 Answers

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.

like image 101
Kracekumar Avatar answered Sep 23 '22 23:09

Kracekumar


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'] 
like image 45
aromanovich Avatar answered Sep 25 '22 23:09

aromanovich