Jinja2 Exception Handling

孤街醉人 提交于 2021-02-04 12:08:08

问题


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!


回答1:


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




回答2:


While jinja2 does not have a way to handle this by default, there is a workaround.

Since try is not supported in the template language, we need a helper function defined in Ppython, like this:

def handle_catch(caller, on_exception):
    try:
         return caller()
    except:
         return on_exception

This method is injected into the template engine, either via the Environment.globals or when calling the render method. In this example it is injected via the render method.

my_template.render(handle_catch=handle_catch)

In the template itself it is then possible to define a macro:

{% macro catch(on_exception) %}
    {{ handle_catch(caller, on_exception) }}
{% endmacro %}

And this can then be used as:

{% for item in items %}
   {% call catch('') %}
       {{ item | custom_urlencode_filter }}
   {% endcall %}
{% endfor %}

Notes:

  • The caller method is provided by the jinja2, and this is a function that renders the code between {% call ... %} and {% endcall %}
  • on_exception can be used to provide an alternative text in case of exceptions, but in this case we just use an empty string.



回答3:


There's none. Just handle the exceptions within the urlencode filter function.



来源:https://stackoverflow.com/questions/21692387/jinja2-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!