Jinja2 ignore UndefinedErrors for objects that aren't found

Building off of Sean's excellent and helpful answer, I did the following:

from jinja2 import Undefined
import logging

class SilentUndefined(Undefined):
    '''
    Dont break pageloads because vars arent there!
    '''
    def _fail_with_undefined_error(self, *args, **kwargs):
        logging.exception('JINJA2: something was undefined!')
        return None

and then env = Environment(undefined=SilentUndefined) where I was calling that.

In the django_jinja library, which I use, the above is in base.py and is actually a modification of initial_params


Jinja2 actually uses a special class for undefined entities. You can subclass this Undefined class from Jinja2 to include __getattr__ and other attribute accessors that you want to be able to use even on undefined entities and have them return a blank unicode string (for example).


I also needed to reset the class's magic methods to make object attributes etc work correctly. Adding to @rattray --

from jinja2 import Undefined, Template

class SilentUndefined(Undefined):
    def _fail_with_undefined_error(self, *args, **kwargs):
        return ''

    __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
        __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
        __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
        __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
        __float__ = __complex__ = __pow__ = __rpow__ = \
        _fail_with_undefined_error        

It'd make sense to be a jinja setting. A lot of people would be coming from django templates which are silent by default.

Tags:

Python

Jinja2