可以使用任意的模板引擎,只需要重载render方法。
默认引擎
会在py文件同级的地方来搜索模板文件,可以通过在app的设置中设置template_path,或者重载get_template_path方法。如果使用的不是文件位置的模板,可以通过派生BaseLoader定义自己的并通过app的template_loader设置。编译好的模板默认是被缓存的,可以在app的设置中通过compiled_template_cache=False关闭或使用debug=True。
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<ul>
{% for item in items %}
<li>{{ escape(item) }}</li>
{% end %}
</ul>
</body>
</html>
class MainHandler(tornado.web.RequestHandler):
def get(self):
items = ["Item 1", "Item 2", "Item 3"]
self.render("template.html", title="My title", items=items)
escape: alias for tornado.escape.xhtml_escape
xhtml_escape: alias for tornado.escape.xhtml_escape
url_escape: alias for tornado.escape.url_escape
json_encode: alias for tornado.escape.json_encode
squeeze: alias for tornado.escape.squeeze
linkify: alias for tornado.escape.linkify
datetime: the Python datetime module
handler: the current RequestHandler object
request: alias for handler.request
current_user: alias for handler.current_user
locale: alias for handler.locale
_: alias for handler.locale.translate
static_url: alias for handler.static_url
xsrf_form_html: alias for handler.xsrf_form_html
reverse_url: alias for Application.reverse_url
All entries from the ui_methods and ui_modules Application settings
Any keyword arguments passed to render or render_string
international
UI
uimodules.py
class Entry(tornado.web.UIModule):
def render(self, entry, show_comments=False):
return self.render_string(
"module-entry.html", entry=entry, show_comments=show_comments)
from . import uimodules
class HomeHandler(tornado.web.RequestHandler):
def get(self):
entries = self.db.query("SELECT * FROM entries ORDER BY date DESC")
self.render("home.html", entries=entries)
class EntryHandler(tornado.web.RequestHandler):
def get(self, entry_id):
entry = self.db.get("SELECT * FROM entries WHERE id = %s", entry_id)
if not entry: raise tornado.web.HTTPError(404)
self.render("entry.html", entry=entry)
settings = {
"ui_modules": uimodules,
}
application = tornado.web.Application([
(r"/", HomeHandler),
(r"/entry/([0-9]+)", EntryHandler),
], **settings)
{% for entry in entries %}
{% module Entry(entry) %}
{% end %}
{% module Entry(entry, show_comments=True) %}
class Entry(tornado.web.UIModule):
def embedded_css(self):
return ".entry { margin-bottom: 1em; }"
def render(self, entry, show_comments=False):
return self.render_string(
"module-entry.html", show_comments=show_comments)
{{ set_resources(embedded_css=".entry { margin-bottom: 1em; }") }}
<!-- more template html... -->
{% module Template("module-entry.html", show_comments=True) %}