Jinja2 Exception Handling

django-templates, exception, jinja2, python, templates

Solution

{% 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

Problem

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!

Original source