Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 ignore UndefinedErrors for objects that aren't found

Tags:

python

jinja2

I switched to Jinja from Django but a lot of my templates broke when referencing

 {{ entity.property }}

if entity is not defined. Is there away to ignore the UndefinedErrors in certain situations, Otherwise I'll have to add in a lot of

 {% if entity %}{{ entity.property }}{% endif %}

wrappers.

Thanks, Richard

like image 873
probably at the beach Avatar asked May 31 '11 16:05

probably at the beach


2 Answers

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

like image 115
rattray Avatar answered Sep 21 '22 15:09

rattray


I built on @rattray's answer above:

from jinja2 import Undefined, Template

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

Then used it with template string:

person_dict = {'first_name': 'Frank', 'last_name': 'Hervert'}
t2 = Template("{{ person1.last_name }}, {{ person.last_name }}", undefined=SilentUndefined)

print t2.render({'person': person_dict})                                                                         
# ', Hervert'

I needed to ignore the errors when rendering a Template from string directly instead of using Environment.

like image 28
Al Conrad Avatar answered Sep 18 '22 15:09

Al Conrad