Jinja2 Exception Handling

后端 未结 3 1403
误落风尘
误落风尘 2020-12-31 08:31

Is there a way to handle exceptions within a template in jinja2?

{% for item in items %}
   {{ item|urlencode }}  <-- item contains a unicode string that          


        
3条回答
  •  渐次进展
    2020-12-31 09:01

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

提交回复
热议问题