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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With