jinja2: How to make it fail Silently like djangotemplate

假如想象 提交于 2019-12-05 10:09:02

You are trying to go arbitrarily deep into your undefined data. menu_links is undefined, so Jinja2 creates a new instance of your UndefinedSilently class. It then calls the __getattr__ method of this object to get the items attribute. This returns a blank unicode string. Which Python then tries to call (the () of menu_links.items()). Which raises the error that unicode objects are not callables.

That is:

menu_links.items() # becomes
UndefinedSilently().items() # becomes
UndefinedSilently().u''() # from UndefinedSilently.__getattr__

If you want to be able to go deeper than one level you can create a class that returns itself for every access attempt except __str__ and __unicode__.

def silently(*args, **kwargs):
    return u''

return_new = lambda *args, **kwargs: UndefinedSilently()

class UndefinedSilently(Undefined):
    __unicode__ = silently
    __str__ = silently
    __call__ = return_new
    __getattr__ = return_new
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!