【问题标题】:How do I use inheritance in Cheetah templates?如何在 Cheetah 模板中使用继承?
【发布时间】:2018-06-21 08:22:21
【问题描述】:

对于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 模板进行继承?

【问题讨论】:

    标签: python templates inheritance cheetah


    【解决方案1】:

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

    1. 使用cheetah compile命令行程序将所有模板编译成*.py文件。然后 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 的最终版本。

    【讨论】:

    • 好的,很酷,谢谢你的回答,博士。当我在上面的示例中添加 from Cheetah import ImportHooksImportHooks.install() 行时,它可以工作。太好了!
    猜你喜欢
    • 2012-06-16
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 2015-04-18
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多