Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Jinja2 convert all UndefinedError exceptions to blank strings?

A lot of the models in my code have relations that can be None. Many times, this requires checks for None before accessing the data:

{% if foo.bar %}
   {{ foo.bar.baz }}
{% endif %}

If I don't add that check, the page breaks completely with an UndefinedError. Is there any way I can fail silently for UndefinedErrors in Jinja2 when run from a Flask app?

like image 262
TheOne Avatar asked Feb 18 '23 15:02

TheOne


1 Answers

Simply create a subclass of jinja2.Undefined that returns itself on attribute access and set it as the Undefined type for your environment by overriding the create_jinja_environment method:

from flask import Flask
from jinja2 import Undefined
from werkzeug.datastructures import ImmutableDict

class MalleableUndefined(Undefined):
    def __getitem__(self, key):
        return self

    def __getattr__(self, key):
        return self


class CustomFlask(Flask):
    def create_jinja_environment(self):
        self.jinja_options = ImmutableDict(undefined=MalleableUndefined, **self.jinja_options)
        return super(CustomFlask, self).create_jinja_environment()
like image 189
Sean Vieira Avatar answered Feb 20 '23 11:02

Sean Vieira