Web.py 模板错误: 'sum' 不存在

3 投票
2 回答
839 浏览
提问于 2025-04-15 16:03

我在使用 web.py 模板里的内置 'sum' 函数时,遇到了以下错误:

global name 'sum' is not defined

下面是源代码:

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

在终端的 Python REPL 中,我使用 'sum' 函数没有问题。

那可能是什么问题呢?

谢谢,
雅各布

2 个回答

0

并不是所有的Python代码都能用模板的方式来写,试试下面这样的写法:

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

把函数放到一个字典里,然后作为全局参数传给渲染函数:

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

然后在你的模板里,你就可以直接使用这些函数了:

$def with (numbers)

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

撰写回答