模板和用户界面

Tornado 可以与任何其他 Python 模板语言一起使用,尽管没有将这些系统集成到 RequestHandler.render 中的规定。只需将模板渲染为字符串并将其传递给 RequestHandler.write 即可。

配置模板

Tornado 在与引用模板文件的 .py 文件相同的目录中查找模板文件。要将模板文件放在不同的目录中,请使用 template_path Application setting(或覆盖 RequestHandler.get_templdate_path)。

要从非文件系统位置加载模板,请子类化 tornado.template.BaseLoader 并传递一个实例作为 template_loaderapplication 设置。

编译好的模板默认会被缓存;要关闭此缓存并重新加载模板,以便对基础文件的更改始终可见,请使用应用程序设置 compiled_template_cache=Falsedebug=True

模板语法

Tornado 模板只是 HTML,其中嵌入了标记中的 Python 控制序列和表达式:

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<ul>
{% for item in items %}
<li>{{ escape(item) }}</li>
{% end %}
</ul>
</body>
</html>

如果您将此模板保存为“template.html”并将其放在与 Python 文件相同的目录中,则可以通过以下方式呈现此模板:

1
2
3
4
class MainHandler(RequestHandler):
def get(self):
items = ["Item1", "Item2", "Item3"]
self.render("template.html", title="Mytitle", items=items)

Tornado 模板支持控制语句和表达式。控制语句由 {%%} 包围,表达式由 {{}} 包围。

控制语句或多或少精确地映射到Python 语句。我们支持 if、for、while 和 try,所有这些都以 {% end %} 终止。

表达式可以是任何 Python 表达式,包括函数调用。模板代码在包含以下对象和函数的命名空间中执行:

别名 德蒂尔
escape escape tornado.escape.xhtml_escape
xhtml_escape xhtml_escape tornado.escape.xhtml_escape
url_escape url_escape 内联_代码_10
json_encode json_encode tornado.escape.json_encode
squeeze squeeze tornado.escape.squeeze
linkify linkify tornado.escape.linkify
datetime datetime
handler handler当前 RequestHandler
request request handler.request
current_user current_user handler.current_user
locale locale handler.locale
_ _ handler.locale.translate
static_url static_url handler.static_url
xsrf_form_html xsrf_form_html handler.xsrf_form_html
reverse_url reverse_url Application.reverse_url

国际化

您可以在模板中使用 _ 来为当前用户进行翻译。

1
_("translate this string.")

用户界面模块

通过