pallets / jinja

A very fast and expressive template engine.

Home Page:https://jinja.palletsprojects.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Enhance Default Exceptions to include Line Number.

rubengm13 opened this issue · comments

commented

When a Built-in Exception is raised, the raised Exception should be modified such that it includes the line number of the Template Line violating the exception.

This Example will trigger a TypeError.

import jinja2
environment = jinja2.Environment()
jinja_template = """
    {%- for name in names %}
        ("HELLO {{name}}!")
    {%- endfor %}
"""
template = environment.from_string(jinja_template)
data = template.render(names=None)
print(data)

Ideally, if we could modify the triggered TypeError Exception to add a lineno attribute so that we can capture the lineno to better track the line number that triggered the issue.

import jinja2
environment = jinja2.Environment()
jinja_template = """
    {%- for name in names %}
        ("HELLO {{name}}!")
    {%- endfor %}
"""
try:
    template = environment.from_string(jinja_template)
    data = template.render(names=None)
except Exception as e:
    print(f"Error on Line Number: {e.lineno}")
print(data)

Happy to review a PR