带有Cherrypy的Cheetah:如何加载基础模板,并在开发过程中自动进行更改

时间:2010-03-31 04:34:08

标签: python template-engine cherrypy cheetah

我正在开发一个cherrypy + cheetah应用程序,并希望改善开发体验。

当我手动编译模板时,我已经完成了所有工作。 (更新:这就是生产工作的方式:预编译,不发送* .tmpl和加载模板作为常规python模块。)但是,在开发过程中我宁愿​​只是在每次引用时加载模板,这样我就不会我需要杀死并重新启动我的应用程序。我遇到了几个问题:

  1. 如果我有从基本模板继承的模板,我会收到导入错误(无法找到基本模板)。我想我在实验期间确实有这个工作,但遗憾的是没有保存它,现在我无法使它工作。
  2. 假设我得到1.工作,如何使它甚至在基本模板中编辑而不重新启动。
  3. 以下是我应该展示问题的示例应用程序。目录结构如下:

    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
    

2 个答案:

答案 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