我有这个:
template = '{{invoice.customer.address.city}}'
而且效果很好。但有时 invoice.customer 为 Null 或 invoice.customer.address 为 Null
然后 jinja 抛出 jinja2.exceptions.UndefinedError: 'None' has no attribute 'address'
因为它无法到达 .city
部分。那么,如果它无法访问属性,我该如何告诉它静默失败呢?
谢谢!
最佳答案
如果您经常这样做,而不是创建每个属性 过滤器,您可以概括 Vor 的答案以适用于任意嵌套 字典,像这样:
import jinja2
def filter_nested_dict(value, default, path):
keys = path.split('.')
for key in keys:
try:
value = value[key]
except KeyError:
return default
return value
env = jinja2.Environment()
env.filters['nested_dict'] = filter_nested_dict
template = env.from_string('''
City: {{invoice|nested_dict('<none>', 'customer.address.city')}}''')
鉴于上述,这:
print template.render(invoice={})
给你:
City: <none>
还有这个:
print template.render(invoice={'customer': {'address': {'city': 'boston'}}})
给你:
City: boston
关于python - 如何处理 Jinja2 中的属性访问错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29083603/