pallets / jinja

A very fast and expressive template engine.
https://jinja.palletsprojects.com
BSD 3-Clause "New" or "Revised" License
10.25k stars 1.6k forks source link

Enhance Default Exceptions to include Line Number. #1861

Open rubengm13 opened 1 year ago

rubengm13 commented 1 year ago

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)
davidism commented 1 year ago

Happy to review a PR