收录日期:2021/01/23 05:43:09 时间:2011-12-01 18:25:56 标签:python,templates,cheetah

For performance reason as suggested here, I am studying how to used the pr-compiled template.

I edit hello.tmpl in template directory as

#attr title = "This is my Template"
<html>
    <head>
        <title>\${title}</title>
    </head>
    <body>
        Hello \${who}!
    </body>
</html>

then issued cheetah-compile.exe .\hello.tmpl and get the hello.py

In another python file runner.py, I have:

#!/usr/bin/env python

from Cheetah.Template import Template
from template import hello
def myMethod():
    tmpl = hello.hello(searchList=[{'who' : 'world'}])
    results = tmpl.respond()
    print tmpl


if __name__ == '__main__':
    myMethod()

But the outcome is

<html>
    <head>
        <title>${title}</title>
    </head>
    <body>
        Hello ${who}!
    </body>
</html>

Debugging for a while, I found that inside hello.py:

def respond(self, trans=None):



    ## CHEETAH: main method generated for this template
    if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
        trans = self.transaction # is None unless self.awake() was called
    if not trans:
        trans = DummyTransaction()

it looks like the trans is None, so it goes to DummyTransaction, what did I miss here? Any suggestions to how to fix it?

Your main problem is that in runner.py inside myMethod() instead of

print tmpl

You need

print results

Additionally, your code has some formatting problems:

  1. don't escape the ${title} with a backslash
  2. you need if __name__ == '__main__': instead of if name == 'main':