如何在Cheetah模板中使用继承?

2024-06-18 13:13:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

假设我有两个模板文件:

A.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模板实现?你知道吗


Tags: 文档模板httpmessagehellodef公司template
1条回答
网友
1楼 · 发布于 2024-06-18 13:13:14

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

  1. 使用cheetah compile命令行程序将所有模板编译成*.py文件。然后导入在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. subversit Python import使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导入首先找到的内容。几天前,我扩展了importhook来自动编译*.tmpl*.py*.pyc。我要写更多的文件,过几天再推。预计几个月后将发布cheetah3.2的最终版本。你知道吗

相关问题 更多 >