OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Make all if statements true in Jinja2 templates

  • Thread starter Thread starter Charma
  • Start date Start date
C

Charma

Guest
I am writing a Jinja2 template validator where I want to check all possibly needed variables. I already implemented my own Undefined class and can successfully detect missing variables, but obviously variables within if-statements are not found.

I do not want to hardcode multiple if-else-cases, so I am wondering if there is a way to make all if-statements true so that I do not check the "else" cases only.

Maybe a way to temporary overwrite the jinja2 function for the {% if %} or something?

Here's my code that detects the used variables:

Code:
def find_all_variables(template_path):
    variables, undefined_cls = create_collector()

try:
    env = Environment(loader = FileSystemLoader(searchpath="./"), autoescape = select_autoescape(),undefined=undefined_cls)
    template = env.get_template(template_path)
    print(template.render({})) # empty so all variables are undefined
except TemplateError as error:
    print(f"Validation of script {template_path} failed:")
    print(error)
    exit(1)

return variables
<p>I am writing a Jinja2 template validator where I want to check all possibly needed variables. I already implemented my own Undefined class and can successfully detect missing variables, but obviously variables within if-statements are not found.</p>
<p>I do not want to hardcode multiple if-else-cases, so I am wondering if there is a way to make all if-statements true so that I do not check the "else" cases only.</p>
<p>Maybe a way to temporary overwrite the jinja2 function for the {% if %} or something?</p>
<p>Here's my code that detects the used variables:</p>
<pre><code>def find_all_variables(template_path):
variables, undefined_cls = create_collector()

try:
env = Environment(loader = FileSystemLoader(searchpath="./"), autoescape = select_autoescape(),undefined=undefined_cls)
template = env.get_template(template_path)
print(template.render({})) # empty so all variables are undefined
except TemplateError as error:
print(f"Validation of script {template_path} failed:")
print(error)
exit(1)

return variables
</code></pre>
 

Latest posts

M
Replies
0
Views
1
Mohit Pant
M
Top