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
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
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.
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