本文介绍了Jinja2异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Jinja2的模板中是否有处理异常的方法?
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?
谢谢!
推荐答案
{% for item in items %}
{{ item | custom_urlencode_filter }}
{% endfor %}
然后在设置jinja2环境的任何文件中
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
这篇关于Jinja2异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!