Cheetah模板引擎调用Python基础函数

1 投票
4 回答
1191 浏览
提问于 2025-04-16 17:21

我正在使用Cheetah模板和Cherrypy,下面是我的主要Python文件

Main.py:
def multiple(a,b):
    return a*b

def index(self):
    t = Template('template.tmpl')
    #blah implementation here

在我的模板文件中,我希望实现

<body>
    <div>
       $multiple(2,3)
    </div>
</body>

有没有人知道我该怎么实现这个?非常感谢。

祝好,
安迪。

4 个回答

1

这可能能解答你的问题:

import Cheetah
import Cheetah.Template


def multiple(a,b):
    return a*b

print Cheetah.Template.Template(file='template.tmpl',
                                searchList=[dict(multiple=multiple)])
2

试试用searchList这个参数:

def index(self):
    t = Template('template.tmpl', searchList=[multiple])

它让你可以定义一些“占位符”,这样你就可以在模板定义中使用它们。

3
t = Template("template.tmpl")
t.multiple = multiple

这样就可以解决问题了。

撰写回答