TheOne
TheOne

Reputation: 11159

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?

Upvotes: 4

Views: 1489

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 160033

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()

Upvotes: 9

Related Questions