问题描述
我没有找到答案,我很确定这很简单,但是我没有找到如何在django中找不到变量的方式工作。
$ b $我尝试使用Undefined并创建我自己的未定义但它给我的属性错误等问题。$ / $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ (* args,** kwargs):
return u''
class UndefinedSilently(Undefined):
__unicode__ =默认
__str__ =默认
__call__ =默认
__getattr__ =静默
但是当我在这里尝试这个失败 TypeError:'unicode'对象不可调用
:
{%for dir_name, menu_links.items()%}
随意深入您未定义的数据。 menu_links
未定义,所以Jinja2创建一个新的 UnrealSilently
类的实例。然后调用该对象的 __ getattr __
方法来获取项目
属性。这将返回一个空白的unicode字符串。哪个Python然后尝试调用($ code code $ c $ menu_links.items())。这引起unicode对象不可调用的错误。
那就是:
menu_links.items()#成为
UndefinedSilently()。items()#成为
UndefinedSilently()。u''()#from UndefinedSilently .__ getattr__
如果您希望能够深入一级,您可以创建一个类,每次访问尝试返回自己,除了 __ str __
和 __ unicode __
。
def (* args,** kwargs):
return u''
return_new = lambda * args,** kwargs:UndefinedSilently()
class UndefinedSilently未定义):
__unicode__ =静默
__str__ =静默
__call__ = return_new
__getattr__ = return_new
Well i dont find the answer i'm shure that it's very simple, but i just dont 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()%}
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
这篇关于jinja2:如何使它失败静默地喜欢djangotemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!