1

对于 Cheetah3,有一个非常粗略的关于继承特性的文档:http ://cheetahtemplate.org/users_guide/inheritanceEtc.html#extends

但我不知道如何让它真正起作用。

假设我有两个模板文件:

tmpl

#def message
Hello Cheetah
#end def
This is an example: $message

B.tmpl

#extends A
#def message
Hello Cheetah with Inheritance
#end def

和一个简单的驱动程序,例如:

from Cheetah.Template import Template

t = Template(file='B.tmpl')
print t

显然,那是行不通的,因为在执行这段代码的时候没有A类。

但进展如何?还是只能使用预编译的 Cheetah 模板进行继承?

4

1 回答 1

1

有两种方法可以从另一个模板导入一个模板。

  1. 使用命令行程序将所有模板编译为*.py文件。cheetah compile然后 import 在 Python 级别工作。

要在编辑所有模板后半自动编译它们,我推荐以下Makefile(GNU 风格):

.SUFFIXES: # Clear the suffix list
.SUFFIXES: .py .tmpl

%.py: %.tmpl
        cheetah compile --nobackup $<
        python -m compile $@

templates = $(shell echo *.tmpl)
modules = $(patsubst %.tmpl,%.py,$(templates))

.PHONY: all
all: $(modules)

(不要忘记——makefile 需要使用制表符缩进,而不是空格。)

  1. 颠覆 Python 导入,让 Cheetah 直接从*.tmpl文件中导入。

代码:

from Cheetah import ImportHooks
ImportHooks.install()

import sys
sys.path.insert(0, 'path/to/template_dir')  # or sys.path.append

PS。ImportHooks 会自动尝试从*.pyc,*.py*.tmpl- 首先找到的任何内容导入。几天前,我扩展了 ImportHooks 以自动编译*.tmpl*.py*.pyc. 我将在几天内编写更多文档并推送。预计几个月后会发布 Cheetah 3.2 的最终版本。

于 2018-06-21T14:00:03.060 回答