Alb*_*ert 13 python templates exception django-templates jinja2
有没有办法在jinja2中处理模板中的异常?
{% for item in items %}
{{ item|urlencode }} <-- item contains a unicode string that contains a character causes urlencode to throw KeyError
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我如何处理该异常,以便我可以跳过该项或处理它而不强制整个模板渲染失败?
谢谢!
Que*_*lan 17
{% for item in items %}
{{ item | custom_urlencode_filter }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
然后在你设置jinja2环境的任何文件中
def custom_urlencode_filter(value):
try:
return urlencode(value)
except:
# handle the exception
environment.filters['custom_urlencode_filter'] = custom_urlencode_filter
Run Code Online (Sandbox Code Playgroud)
有关自定义jinja2过滤器的更多信息
虽然 jinja2 默认情况下没有办法处理这个问题,但有一个解决方法。
由于try模板语言不支持,我们需要一个在Python中定义的辅助函数,如下所示:
def handle_catch(caller, on_exception):
try:
return caller()
except:
return on_exception
Run Code Online (Sandbox Code Playgroud)
该方法通过Environment.globals或 在调用 render 方法时注入到模板引擎中。在此示例中,它是通过 render 方法注入的。
my_template.render(handle_catch=handle_catch)
Run Code Online (Sandbox Code Playgroud)
然后可以在模板本身中定义一个宏:
{% macro catch(on_exception) %}
{{ handle_catch(caller, on_exception) }}
{% endmacro %}
Run Code Online (Sandbox Code Playgroud)
然后这可以用作:
{% for item in items %}
{% call catch('') %}
{{ item | custom_urlencode_filter }}
{% endcall %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
笔记:
{% call ... %}和之间代码的函数{% endcall %}| 归档时间: |
|
| 查看次数: |
11270 次 |
| 最近记录: |