我有以下代码来测试模板渲染:
import os
from tornado.template import Loader
class A:
def __init__(self):
self.loader = Loader(os.path.join(os.path.dirname(__file__), "templates"))
def simple_template(self):
tmpl = self.loader.load("utf8.html")
result = tmpl.generate()
print result
def complex_template(self, message):
tmpl = self.loader.load("message.html")
result = tmpl.generate(message = message)
print result
a = A()
a.simple_template()
a.complex_template({"id" : 'asdsadfasd', "from": 'sdfsafd', "body": 'sdfdasfd'})
这些是我的模板:
模板/utf8.html
Héllo
模板/message.html
<div class="message" id="m{{ message["id"] }}"><b>{{ message["from"] }}: </b>{% module linkify(message["body"]) %}</div>
这是输出:
Héllo
ERROR:root:message.html code:
1 def _execute(): # message.html:0
2 _buffer = [] # message.html:0
3 _append = _buffer.append # message.html:0
4 _append('<div class="message" id="m') # message.html:1
5 _tmp = message["id"] # message.html:1
6 if isinstance(_tmp, _string_types): _tmp = _utf8(_tmp) # message.html:1
7 else: _tmp = _utf8(str(_tmp)) # message.html:1
8 _tmp = _utf8(xhtml_escape(_tmp)) # message.html:1
9 _append(_tmp) # message.html:1
10 _append('"><b>') # message.html:1
11 _tmp = message["from"] # message.html:1
12 if isinstance(_tmp, _string_types): _tmp = _utf8(_tmp) # message.html:1
13 else: _tmp = _utf8(str(_tmp)) # message.html:1
14 _tmp = _utf8(xhtml_escape(_tmp)) # message.html:1
15 _append(_tmp) # message.html:1
16 _append(': </b>') # message.html:1
17 _tmp = _modules.linkify(message["body"]) # message.html:1
18 if isinstance(_tmp, _string_types): _tmp = _utf8(_tmp) # message.html:1
19 else: _tmp = _utf8(str(_tmp)) # message.html:1
20 _append(_tmp) # message.html:1
21 _append('</div>\n') # message.html:2
22 return _utf8('').join(_buffer) # message.html:0
Traceback (most recent call last):
File "template_test2.py", line 21, in <module>
a.complex_template({"id" : 'asdsadfasd', "from": 'sdfsafd', "body": 'sdfdasfd'})
File "template_test2.py", line 16, in complex_template
result = tmpl.generate(message = message)
File "/home/gonvaled/.virtualenvs/python2.7.2-wavilon1/lib/python2.7/site-packages/tornado/template.py", line 254, in generate
return execute()
File "message_html.generated.py", line 17, in _execute
NameError: global name '_modules' is not defined
如您所见,简单模板按预期呈现,但复杂模板失败。如何在不定义应用程序的情况下呈现复杂的模板?在这种情况下,我只想使用 tornado 的模板渲染工具。