我使用一个名为的变量x,x未定义,并用于x与mako模板中的数字进行比较:
%if x>5:
<h1>helloworld</h1>
%endif
Run Code Online (Sandbox Code Playgroud)
为什么这句话不会导致异常或错误?但是当我想打印出来的时候:
%if x>5:
<h1>${x}</h1>
%endif
Run Code Online (Sandbox Code Playgroud)
它引起了例外.为什么?
这是在mako.为什么我不能在IPython中使用这句话?因为如果我在IPython中使用未定义的变量,它会告诉我变量没有突然定义.
那是因为mako默认情况下使用的Undefined对象只在渲染时失败,但可以在布尔表达式中使用,因为它实现了__nonzero__方法:
class Undefined(object):
"""Represents an undefined value in a template.
All template modules have a constant value
``UNDEFINED`` present which is an instance of this
object.
"""
def __str__(self):
raise NameError("Undefined")
def __nonzero__(self):
return False
UNDEFINED = Undefined()
Run Code Online (Sandbox Code Playgroud)
要使用即使在布尔表达式中失败的未定义值,也可以使用strict_undefined如下参数:
>>> from mako.template import Template
>>> mytemplate = Template("""%if x>5:
... <h1>helloworld</h1>
... %endif""", strict_undefined=True)
>>> mytemplate.render()
...
NameError: 'x' is not defined
Run Code Online (Sandbox Code Playgroud)
需要注意的是strict_undefined在这两个可mako.template.Template及mako.lookup.TemplateLookup.
文档中的描述是:
替换为不存在于Context中的任何未声明变量的UNDEFINED的自动使用,并立即引发NameError.优点是立即报告包含名称的缺失变量.新增0.3.6.