1、在模板中使用占位符
在模板中,使用 {{占位符 }} 来表示要填充的内容,其中的占位符在模板调用时定义并进行实际的填充,例如:
<!DOCTYPE html>
<html>
<head><title>Poem Maker Pro</title></head>
<body>
<h1>Your poem</h1>
<p>Two {{roads}} diverged in a {{wood}}, and I—<br>
I took the one less travelled by,<br>
And that has {{made}} all the {{difference}}.</p>
</body>
</html>
其中,{{ }}中的内容,会在进行模板调用时,进行实际的填充
2、在模板中使用控制流语句
在模板中,不仅可以使用占位符,还可以直接使用python语句进行控制,其中的python语句要放在{% python语句 % },其中以if 、for、while等控制流语句使用最多,例如:
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ header }}</h1>
<ul>
{% for book in books %}
<li>{{ book }}</li>
{% end %}
</ul>
</body>
</html>
3、在模板中使用函数
在模板中可以直接使用以下内嵌函数,进行一些处理
escape(s)
替换字符串s中的&、<、>为他们对应的HTML字符。
url_escape(s)
使用urllib.quote_plus替换字符串s中的字符为URL编码形式。
json_encode(val)
将val编码成JSON格式。(在系统底层,这是一个对json库的dumps函数的调用。查阅相关的文档以获得更多关于该函数接收和返回参数的信息。)
squeeze(s)
过滤字符串s,把连续的多个空白字符替换成一个空格。也可以在python文件中自定义一些函数,在模板调用时,直接将函数名传给模板即可
4、模板的调用和渲染
模板的调用很简单,直接在请求处理类中调用render函数即可。
例如:
(1) 简单返回一个模板,不需要渲染
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
(2)进行占位符渲染
class BookHandler(tornado.web.RequestHandler):
def get(self):
self.render(
"book.html",
title="Home Page",
header="Books that are great",
books=[
"Learning Python",
"Programming Collective Intelligence",
"Restful Web Services"
]
)
(3)进行自定义函数渲染
>>> from tornado.template import Template
>>> def disemvowel(s):
... return ''.join([x for x in s if x not in 'aeiou'])
...
>>> disemvowel("george")
'grg'
>>> print Template("my name is {{d('mortimer')}}").generate(d=disemvowel)
my name is mrtmr
5、模板文件的路径设置
在进行Application类的实例化时,进行模板路径的设置:
app = tornado.web.Application(
handlers=[(r'/', IndexHandler), (r'/poem', MungedPageHandler)],
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True
)
设置了模板路径后,在render函数调用模板时,直接在该路径下寻找
6、模板中的静态文件路径
在进行Application类的实例化时,进行静态路径的设置
app = tornado.web.Application(
handlers=[(r'/', IndexHandler), (r'/poem', MungedPageHandler)],
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True
)
在设置了静态路径后,在模板文件中,可调用static_url()函数,获得静态文件的全路径:
<link rel="stylesheet" href="{{ static_url("style.css") }}">
这个对static_url的调用生成了URL的值,并渲染输出类似下面的代码:
<link rel="stylesheet" href="/static/style.css?v=ab12">
为什么使用static_url而不是在你的模板中硬编码呢?有如下几个原因。其一,static_url函数创建了一个基于文件内容的hash值,并将其添加到URL末尾(查询字符串的参数v)。这个hash值确保浏览器总是加载一个文件的最新版而不是之前的缓存版本。无论是在你应用的开发阶段,还是在部署到生产环境使用时,都非常有用,因为你的用户不必再为了看到你的静态内容而清除浏览器缓存了。
另一个好处是你可以改变你应用URL的结构,而不需要改变模板中的代码。
7、一个完整的实例
用户输入两个文本:一个"源"文本和一个"替代"文本。应用会返回替代文本的一个副本,并将其中每个单词替换成源文本中首字母相同的某个单词。
这个应用包括四个文件:main.py(Tornado程序)、style.css(CSS样式表文件)、index.html和munged.html(Tornado模板)。
import os.path import random import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, options define("port", default=8000, help="run on the given port", type=int) class IndexHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') class MungedPageHandler(tornado.web.RequestHandler): def map_by_first_letter(self, text): mapped = dict() for line in text.split('\r\n'): for word in [x for x in line.split(' ') if len(x) > 0]: if word[0] not in mapped: mapped[word[0]] = [] mapped[word[0]].append(word) return mapped def post(self): source_text = self.get_argument('source') text_to_change = self.get_argument('change') source_map = self.map_by_first_letter(source_text) change_lines = text_to_change.split('\r\n') self.render('munged.html', source_map=source_map, change_lines=change_lines, choice=random.choice) if __name__ == '__main__': tornado.options.parse_command_line() app = tornado.web.Application( handlers=[(r'/', IndexHandler), (r'/poem', MungedPageHandler)], template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), debug=True ) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{{ static_url("style.css") }}"> <title>The Alpha Munger</title> </head> <body> <h1>The Alpha Munger</h1> <p>Enter two texts below. The replacement text will have its words replaced by words beginning with the same letter in the source text.</p> <form method="post" action="/poem"> <p>Source text<br> <textarea rows=4 cols=55 name="source"></textarea></p> <p>Text for replacement<br> <textarea rows=4 cols=55 name="change"></textarea></p> <input type="submit"> </form> </body> </html>
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{{ static_url("style.css") }}"> <title>The Alpha Munger</title> </head> <body> <h1>Your text</h1> <p> {% for line in change_lines %} {% for word in line.split(' ') %} {% if len(word) > 0 and word[0] in source_map %} <span class="replaced" title="{{word}}">{{ choice(source_map[word[0]]) }}</span> {% else %} <span class="unchanged" title="unchanged">{{word}}</span> {% end %} {% end %} <br> {% end %} </p> </body> </html>
body {
font-family: Helvetica,Arial,sans-serif;
width: 600px;
margin: 0 auto;
}
.replaced:hover { color: #00f; }