【问题标题】:why an undefined variable is larger than a number in mako template?为什么未定义的变量大于 mako 模板中的数字?
【发布时间】:2012-02-02 07:11:54
【问题描述】:

我使用了一个名为x的变量,x没有定义,并使用x与mako模板中的一个数字进行比较:

 %if x>5:
    <h1>helloworld</h1>
 %endif

为什么这句话不会引起异常或错误?但是当我想打印出来时:

%if x>5:
    <h1>${x}</h1>
%endif

它导致了异常。为什么?

这是在mako。为什么我不能在 IPython 中使用这句话?因为如果我在 IPython 中使用未定义的变量,它会突然告诉我变量没有定义。

【问题讨论】:

  • 能否请您发布这个给出的例外情况?

标签: python mako


【解决方案1】:

这是因为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()

要使用即使在布尔表达式中也失败的未定义值,您可以使用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

请注意,strict_undefinedmako.template.Templatemako.lookup.TemplateLookup 中都可用。

来自documentation的描述是:

使用立即引发 NameError 替换未位于上下文中的任何未声明变量的自动使用 UNDEFINED。优点是立即报告包含名称的缺失变量。 0.3.6 中的新功能。

【讨论】:

  • @RaymondHettinger 谢谢,我很感激。
  • 非常感谢,你的回答对我帮助很大
猜你喜欢
  • 2012-04-21
  • 2012-08-14
  • 2014-06-27
  • 1970-01-01
  • 2018-12-02
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多