我正在开发一个cherrypy + cheetah应用程序,并希望改善开发体验。
当我手动编译模板时,我已经完成了所有工作。 (更新:这就是生产工作的方式:预编译,不发送* .tmpl和加载模板作为常规python模块。)但是,在开发过程中我宁愿只是在每次引用时加载模板,这样我就不会我需要杀死并重新启动我的应用程序。我遇到了几个问题:
以下是我应该展示问题的示例应用程序。目录结构如下:
t.py
templates/
base.tmpl
index.tmpl
t.py:
import sys
import cherrypy
from Cheetah.Template import Template
class T:
def __init__(self, foo):
self.foo = foo
@cherrypy.expose
def index(self):
return Template(file='templates/index.tmpl',
searchList=[{'foo': self.foo}]).respond()
cherrypy.quickstart(T(sys.argv[1]))
base.tmpl:
#def body
This is the body from the base
#end def
This is the base doc
index.tmpl:
#from templates.base import base
#extends base
#def body
$base.body(self)
This is the extended body
#end def
This is from index
像这样运行:
python t.py Something
答案 0 :(得分:1)
试试这个:
将base.tmpl
替换为:
#from Cheetah.Template import Template
#def body
#set $base = Template(file="templates/base.tmpl")
$base.body()
<br/>
This is the extended body
#end def
$body()
<br/>
This is from index
答案 1 :(得分:1)
看起来这个问题在另一个SO问题中得到了回答。通过使用cheetah_import函数,我可以编写这样的方法:
@cherrypy.expose
def index(self):
templates = cheetah_import('templates.index')
t = getattr(getattr(templates, 'index'), 'index')(searchList=[{'foo': self.foo}])
return t.respond()
我还需要在模板目录中添加__init__.py
。此方法还要求Cherrypy的engine.autoreload_on
设置设置为True
。
为了提高效率,我可以制作cheetah_import = __import__
而不是替换默认的__builtin__.import
。