【问题标题】:Web.py template error: 'sum' does not existWeb.py 模板错误:“总和”不存在
【发布时间】:2009-11-16 09:23:03
【问题描述】:

我在 web.py 模板模板中使用了内置的“sum”函数,但出现以下错误:

global name 'sum' is not defined

源码如下:

$if profs:
   $for prof in profs:
      $sum([1, 2, 3])

我可以在终端的 Python REPL 中很好地使用“sum”。

可能是什么问题?

谢谢, 雅各布

【问题讨论】:

    标签: python web.py


    【解决方案1】:

    在字典中添加函数并作为全局参数传递给渲染:

    render = web.template.render('templates/', globals={'sum': sum})
    

    然后在你的模板中你就可以使用它了:

    $def with (numbers)
    
    <h1>Numbers add to $sum(numbers)</h1>
    

    【讨论】:

      【解决方案2】:

      并非所有 python 代码都可以在模板表示法中使用,请尝试以下操作:

      $if profs:
         $for prof in profs:
            $code:
               mysum = sum([1, 2, 3])
            $mysum
      

      【讨论】:

      • 不,错误仍然存​​在。我只想总结一个列表,我认为这将是模板中允许的 Python 子集的一部分,但也许我错了。
      • 模板语言通常不允许直接实例化函数调用。您可能需要提前分配 sum 值,例如通过属性或方法。
      猜你喜欢
      • 2014-06-18
      • 2016-11-07
      • 1970-01-01
      • 2014-10-18
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多