Cheetah 模板导入函数

2 投票
1 回答
818 浏览
提问于 2025-04-16 19:02

我在使用Cheetah模板时遇到了一些问题,想要导入函数并在模板中运行它们。

我有一个文件在这个路径:/docroot/tmpl/base.html,另一个文件在这个路径:/docroot/tmpl/comments.html。

在comments.html文件里,我有一些代码,看起来像这样:

#def generateComments($commentObj):
 code for generating comments
#end def

然后在base.html文件里,我想用这样的语法:

#import docroot.tmpl.comments as comments
<div class="commentlist">
 $comments.generateComments($commentObj)
</div>

但是当我运行这个输出时,我只看到comments.html的内容被打印出来,包括#def generateComments的原始文本。

我缺少了什么呢?

1 个回答

1

Cheetah 是一个可以把模板编译成 Python 类的工具。当你导入 comments 模块时,这个模块里面只有一个类,也叫 comments。你需要明确地创建这个类的一个实例,然后调用它的 generateComments 方法。所以你的代码应该是这样的:

#from docroot.tmpl import comments
<div class="commentlist">
 $comments.comments().generateComments($commentObj)
</div>

这里第一个 comments 是模块名,comments.comments 是模块里的模板类,comments.comments() 是这个类的一个实例,而 comments.comments().generateComments($commentObj) 则是调用这个实例的方法。为了让代码更简单一点,可以直接导入这个类:

#from docroot.tmpl.comments import comments
<div class="commentlist">
 $comments().generateComments($commentObj)
</div>

撰写回答