Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 Exception Handling

Is there a way to handle exceptions within a template in jinja2?

{% for item in items %}
   {{ item|urlencode }}  <-- item contains a unicode string that contains a character causes urlencode to throw KeyError
{% endfor %}

How do I handle that exception so that I can just skip that item or handle it without forcing the entire template rendering to fail?

Thanks!

like image 330
Albert Avatar asked Feb 11 '14 03:02

Albert


People also ask

What does Jinja Autoescape do?

It also enables autoescaping for HTML files. This loader only requires that yourapp is importable, it figures out the absolute path to the folder for you.

Is Jinja an API?

The high-level API is the API you will use in the application to load and render Jinja2 templates. The Low Level API on the other side is only useful if you want to dig deeper into Jinja2 or develop extensions. The core component of Jinja is the Environment .

What is the difference between Jinja and Jinja2?

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.


Video Answer


1 Answers

{% for item in items %}
   {{ item | custom_urlencode_filter }}
{% endfor %}

Then in whatever file you have setting up your jinja2 environment

def custom_urlencode_filter(value):
    try:
        return urlencode(value)
    except:
        # handle the exception


environment.filters['custom_urlencode_filter'] = custom_urlencode_filter

More on custom jinja2 filters

like image 122
Quentin Donnellan Avatar answered Oct 05 '22 11:10

Quentin Donnellan