1. 路径与渲染
使用模板,需要仿照静态文件路径设置一样,向web.Application类的构造函数传递一个名为template_path的参数来告诉Tornado从文件系统的一个特定位置提供模板文件,如:
app = tornado.web.Application(
[(r'/', IndexHandler)],
static_path=os.path.join(os.path.dirname(__file__), "statics"),
template_path=os.path.join(os.path.dirname(__file__), "templates"),
)
在这里,我们设置了一个当前应用目录下名为templates的子目录作为template_path的参数。在handler中使用的模板将在此目录中寻找。
现在我们将静态文件目录statics/html中的index.html复制一份到templates目录中,此时文件目录结构为: 在handler中使用render()方法来渲染模板并返回给客户端。
class IndexHandler(RequestHandler):
def get(self):
self.render("index.html") # 渲染主页模板,并返回给客户端。
current_path = os.path.dirname(__file__)
app = tornado.web.Application(
[
(r'^/$', IndexHandler),
(r'^/view/(.*)$', StaticFileHandler, {"path":os.path.join(current_path, "statics/html")}),
],
static_path=os.path.join(current_path, "statics"),
template_path=os.path.join(os.path.dirname(__file__), "templates"),
)
2. 模板语法
2-1 变量与表达式
在tornado的模板中使用{{}}作为变量或表达式的占位符,使用render渲染后占位符{{}}会被替换为相应的结果值。
我们将index.html中的一条房源信息记录
¥398/晚
宽窄巷子+160平大空间+文化保护区双地铁
整套出租 - 5分/6点评 - 北京市丰台区六里桥地铁
改为模板:
¥{{price}}/晚
{{title}}
整套出租 - {{score}}分/{{comments}}点评 - {{position}}
渲染方式如下:
class IndexHandler(RequestHandler):
def get(self):
house_info = {
"price": 398,
"title": "宽窄巷子+160平大空间+文化保护区双地铁",
"score": 5,
"comments": 6,
"position": "北京市丰台区六里桥地铁"
}
self.render("index.html", **house_info)
{{}}不仅可以包含变量,还可以是表达式,如:
¥{{p1 + p2}}/晚
{{"+".join(titles)}}
整套出租 - {{score}}分/{{comments}}点评 - {{position}}
class IndexHandler(RequestHandler):
def get(self):
house_info = {
"p1": 198,
"p2": 200,
"titles": ["宽窄巷子", "160平大空间", "文化保护区双地铁"],
"score": 5,
"comments": 6,
"position": "北京市丰台区六里桥地铁"
}
self.render("index.html", **house_info)
2-2 控制语句
可以在Tornado模板中使用Python条件和循环语句。控制语句以{%和%}包围,并以类似下面的形式被使用:
{% if page is None %}
或
{% if len(entries) == 3 %}
控制语句的大部分就像对应的Python语句一样工作,支持if、for、while,注意end:
{% if ... %} ... {% elif ... %} ... {% else ... %} ... {% end %}
{% for ... in ... %} ... {% end %}
{% while ... %} ... {% end %}
再次修改index.html:
{% if len(houses) > 0 %}
{% for house in houses %}
¥{{house["price"]}}/晚
{{house["title"]}}
整套出租 - {{house["score"]}}分/{{house["comments"]}}点评 - {{house["position"]}}
{% end %}
{% else %}
对不起,暂时没有房源。
{% end %}
python中渲染语句为:
class IndexHandler(RequestHandler):
def get(self):
houses = [
{
"price": 398,
"title": "宽窄巷子+160平大空间+文化保护区双地铁",
"score": 5,
"comments": 6,
"position": "北京市丰台区六里桥地铁"
},
{
"price": 398,
"title": "宽窄巷子+160平大空间+文化保护区双地铁",
"score": 5,
"comments": 6,
"position": "北京市丰台区六里桥地铁"
},
{
"price": 398,
"title": "宽窄巷子+160平大空间+文化保护区双地铁",
"score": 5,
"comments": 6,
"position": "北京市丰台区六里桥地铁"
},
{
"price": 398,
"title": "宽窄巷子+160平大空间+文化保护区双地铁",
"score": 5,
"comments": 6,
"position": "北京市丰台区六里桥地铁"
},
{
"price": 398,
"title": "宽窄巷子+160平大空间+文化保护区双地铁",
"score": 5,
"comments": 6,
"position": "北京市丰台区六里桥地铁"
}]
self.render("index.html", houses=houses)
2-3 函数
static_url()
Tornado模板模块提供了一个叫作static_url的函数来生成静态文件目录下文件的URL。如下面的示例代码:
关注
打赏