tornado本身非常灵活,支持几乎所有python支持的模板语言。除此之外,它本身也提供了一个轻量级的模板,放在tornado.template
中。
代码清单1:tornado_template.py
import tornado.httpserver
import tornado.ioloop
import tornado.web
# define one "add" customization funcation which will be used in the assigned template file.
def add(x, y):
return (x+y)
class MainHandler(tornado.web.RequestHandler):
def get(self):
items = ["item1","item2","item3"]
# render the corresponding template file, and pass the "**args" to the assigned template
# not only we can pass the realted parameters, but also can pass the related functions.
# so extendible and powerful! :)
items2 = ["item1", "item2"]
def checked(item):
return 'checked=checked' if item in items2 else ''
self.render("template_test.html", items=items, add=add, items2=items2, checked=checked)
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8081)
tornado.ioloop.IOLoop.instance().start()
代码清单2:template_test.html
<html>
<head>
<title>template function testtitle>
head>
<body>
<ul>
{% for item in items %}
<li>{{ escape(item) }}li>
<li> <input value={{item}} name={{item}} type="checkbox" {{checked(item)}} /> {{item}}li>
{% end %}
{{ add(2,2) }}
ul>
body>
html>
在同一文件夹中创建如上两个文件,然后在命令行运行python tornado_temp_test.py
,再在浏览器打开localhost:8081
,可以看到如下界面:
<html>
<head>
<title>template function testtitle>
head>
<body>
<ul>
<li>item1li>
<li> <input value=item1 name=item1 type="checkbox" checked=checked /> item1li>
<li>item2li>
<li> <input value=item2 name=item2 type="checkbox" checked=checked /> item2li>
<li>item3li>
<li> <input value=item3 name=item3 type="checkbox" /> item3li>
4
ul>
body>
html>
self.render("template_test.html", items=items, add=add, items2=items2, checked=checked)
来渲染模板,其中render
的第一个参数为模板文件,后面的所有参数会被传入模板文件中。此处可以将其他所有参数放入一个参数中,然后用参数解析语法**kwargs
来传入。如此处的调用等价于: kwargs = {
'items': items,
'items2': items2,
'add':add,
'checked':checked
}
self.render("template_test.html", **kwargs)
{% for item in items %} ... {% end %}
:相当于python中的for
语句。{{ add(2,2) }}
执行了python中的add(2, 2)
,将结果放在此处,即图中我们看到的4
。{{checked(item)}}
同理。value={{item}}
将循环中产生的item
赋给value,查看网页源代码可知
被解析成了
Template expressions are surrounded by double curly braces: {{ ... }}
. The contents may be any python expression, which will be escaped according to the current autoescape setting and inserted into the output. Other template directives use{% %}
. These tags may be escaped as {{!
and {%!
if you need to include a literal {{
or {%
in the output.
To comment out a section so that it is omitted from the output, surround it with {# ... #}
.
{% apply *function* %}...{% end %}
Applies a function to the output of all template code between apply and end:
{% apply linkify %}{{name}} said: {{message}}{% end %}
{% autoescape *function* %}
Sets the autoescape mode for the current file. This does not affect other files, even those referenced by{% include %}
. Note that autoescaping can also be configured globally, at the Application or Loader.:
{% autoescape xhtml_escape %}
{% autoescape None %}
{% block *name* %}...{% end %}
Indicates a named, replaceable block for use with {% extends %}. Blocks in the parent template will be replaced with the contents of the same-named block in a child template.:
<title>{% block title %}Default title{% end %}title>
{% extends "base.html" %}
{% block title %}My page title{% end %}
{% comment ... %}
A comment which will be removed from the template output. Note that there is no {% end %} tag; the comment goes from the word comment to the closing %} tag.
{% extends *filename* %}
Inherit from another template. Templates that use extends should contain one or more block tags to replace content from the parent template. Anything in the child template not contained in a block tag will be ignored. For an example, see the {% block %} tag.
{% for *var* in *expr* %}...{% end %}
Same as the python for statement.
{% from *x* import *y* %}
Same as the python import statement.
{% if *condition* %}...{% elif *condition* %}...{% else %}...{% end %}
Conditional statement - outputs the first section whose condition is true. (The elif and else sections are optional)
{% import *module* %}
Same as the python import statement.
{% include *filename* %}
Includes another template file. The included file can see all the local variables as if it were copied directly to the point of the include directive (the{% autoescape %}
directive is an exception). Alternately, {% module Template(filename, **kwargs) %}
may be used to include another template with an isolated namespace.
{% module *expr* %}
Renders a UIModule. The output of the UIModule is not escaped:
{% module Template("foo.html", arg=42) %}
{% raw *expr* %}
Outputs the result of the given expression without autoescaping.
{% set *x* = *y* %}
Sets a local variable.
{% try %}...{% except %}...{% finally %}...{% else %}...{% end %}
Same as the python try statement.
{% while *condition* %}... {% end %}
Same as the python while statement.
【1】:template@tornado 学习记录
【2】:Introduction to Tornado中文版相关内容
【3】:官方文档中的相关内容