jinja2:如何让它像djangotemplate一样默默地失败
好吧,我没有找到答案,我确信它非常简单,但我只是不知道如何让它像 Django 一样工作,当它找不到
我尝试使用 Undefined 并创建我自己的 undefined 的 变量时但它给了我属性错误等问题。
def silently(*args, **kwargs):
return u''
class UndefinedSilently(Undefined):
__unicode__ = silently
__str__ = silently
__call__ = silently
__getattr__ = silently
但是当我在这里尝试这个时,它失败了 TypeError: 'unicode' object is not callable
:
{%for dir_name, links in menu_links.items()%}
Well i don't find the answer I'm sure that it's very simple, but i just don't find out how to make it work like Django when it doesn't find a variable
i tried to use Undefined and create my own undefined but it give me problems of attribute error etc.
def silently(*args, **kwargs):
return u''
class UndefinedSilently(Undefined):
__unicode__ = silently
__str__ = silently
__call__ = silently
__getattr__ = silently
but when i try this here it fails TypeError: 'unicode' object is not callable
:
{%for dir_name, links in menu_links.items()%}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正试图任意深入未定义的数据。
menu_links
未定义,因此 Jinja2 创建UndefinedSilently
类的新实例。然后,它调用该对象的 __getattr__ 方法来获取items
属性。这将返回一个空白的 unicode 字符串。然后 Python 尝试调用(menu_links.items()
的()
)。这会引发 unicode 对象不可调用的错误。也就是说:
如果您希望能够比一个级别更深,您可以创建一个类,该类对于除
__str__
和__unicode__
之外的每次访问尝试都返回自身。You are trying to go arbitrarily deep into your undefined data.
menu_links
is undefined, so Jinja2 creates a new instance of yourUndefinedSilently
class. It then calls the__getattr__
method of this object to get theitems
attribute. This returns a blank unicode string. Which Python then tries to call (the()
ofmenu_links.items()
). Which raises the error that unicode objects are not callables.That is:
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__
.这是一个老问题,但它解决了一个相关问题。我重温/回答这个问题是为了帮助其他人参考Django 3.1/3.2/4.0:
转到您的
settings.py
。在“选项”中添加以下内容:
这样,未定义的变量在渲染时将不会出现,即“沉默”。完整的代码应如下所示:
或者,您可以使用
DebugUndefined
查看未定义的变量,或使用'StrictUndefine'
在使用未定义变量的情况下引发异常。This is an old question, but it addresses a relevant issue. I revive/answer this to assist others with reference to Django 3.1/3.2/4.0:
Go to your
settings.py
.Add in 'OPTIONS' the following:
With this, undefined variables will not appear when rendered, i.e. be 'silent'. The full code should look something like this:
Alternatively, you can use
DebugUndefined
to see undefined variables, or'StrictUndefined'
to raise exceptions where undefined variables are used.