擅长:python、mysql、java
<p>虽然jinja2在默认情况下没有办法处理这个问题,但是有一个解决方法。</p>
<p>由于模板语言不支持try,我们需要在python中定义一个helper函数,如下所示:</p>
<pre><code> def handle_catch(caller, on_exception):
try:
return caller()
except:
return on_exception
</code></pre>
<p>此方法通过Environment.globals或在调用render方法时注入模板引擎。在本例中,它是通过render方法注入的。</p>
<pre><code>my_template.render(handle_catch=handle_catch)
</code></pre>
<p>然后可以在模板本身中定义宏:</p>
<pre><code>{% macro catch(on_exception) %}
{{ handle_catch(caller, on_exception) }}
{% endmacro %}
</code></pre>
<p>这可以用作:</p>
<pre><code>{% for item in items %}
{% call catch('') %}
{{ item | custom_urlencode_filter }}
{% endcall %}
{% endfor %}
</code></pre>
<p>注:</p>
<ul>
<li>调用方方法由jinja2提供,这是一个在{%call。。。%}以及{%endcall%}</li>
<li>on_exception可用于在出现异常时提供替代文本,但在这种情况下,我们只使用空字符串。</li>
</ul>