Tornado自身提供了tornado.template模块,这是一个轻量级、快速并且灵活的模板语言。
1.控制语句流,在Tornado模板中可以使用Python条件和循环语句,都以{% 和 %}包围,例子如下:
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ header }}</h1>
<ul>
{% for book in books %}
<li>{{ book }}</li>
{% end %}
</ul>
</body>
</html>
2.静态路径
static_path参数指定了放置静态资源(如图像、CSS文件、JavaScript文件等)的目录。,例如:
static_path=os.path.join(os.path.dirname(__file__), "static"),
而在Tornado模板模块又提供了一个叫作static_url的函数来生成static目录下文件的URL,如:
<link rel="stylesheet" href="{{ static_url("style.css") }}">
也就相当于<link rel="stylesheet" href = "XXX/XXX/XXX/style.css">
不过相比后者,前者具备更多的优点,比如方便动态更新等等,自己揣摩。
3.对于模板文件的引入,例如:
template_path = os.path.join(os.path.dirname(__file__), "templates")#指示系统在Tornado文件同目录下的templates文件夹中寻找模板文件
template_path告诉Tornado去哪里寻找模板,也就是一个嵌入Python代码片段的HTML文件,类似于PHP一样是一种嵌入的语言。举一个简单的小例子,拓展一下可以实现“评论”等等的功能,不过这样的功能是静态的,实现更好的效果应该使用AJAX来实现无跳转的更新数据,这些虽然只是很简单的例子,但是却反映了本质的内容,经过扩展应该能实现一定的功能。在这其中,双大括号{{ x }}中的单词是占位符,当我们渲染模板时希望以实际值代替,当然,里面可以放任何Python表达式;
在进行页面渲染之前,向render函数中传递关键字参数的方法指定什么值将被填充到HTML文件中的对应位置,其中关键字对应模板文件中占位符的名字,例如,即在poem.html页面中,将addComment替换成comment的值:
self.render('poem.html', addComment = comment)
python文件,定义逻辑:
class CommentHandler(tornado.web.RequestHandler):
def post(self):
comment = self.get_argument('comment')
self.render('poem.html', addComment = comment)
首页,用于输入评论:
<!DOCTYPE html>
<html>
<head><title>Comment</title></head>
<body>
<h1>please input your comment</h1>
<form method="post" action="/poem">
<p>Add comments<br>
<input type="text" name="comment"></p>
<input type="submit">
</form>
</body>
</html>
跳转后的页面,用于显示评论
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<h1>Your comment</h1>
<p>{{addComment}}</p>
</body>
</html>