Tornado模板模块{
一般流程
- 继承模板: 一个html(模板)文件中 只能有一个继承 {% extends %}
- 复写:①在一个模板(html)中,可以添加很多{% block 块名 %}...{% endblock %} 模块;②在继承的模板中,可以通过 块名 进行重写(替换)块的内容;③ 在继承的模板中可以 ,也可以通过{% block。super %}{{ block.super }}...{% endblock %} 追加块内容
- 加载模板(html):和继承不同,一个html(模板)中可以加载多个模板(html)
- 模块调用(model):model是一个对象,在html中的model 会去调用对应的class中render函数 替换model部分
一、继承
{% extends 模板名 %}
继承模板,列子:
在index.html中
{% extends base.html %}
二、复写模板内容
{% block 块名 %} {% endblock %}
块,例子:
在base.html中
{% block head %}
<meta charset="gdb">
{% endblock %}
在index.html中
{% extends base.html %}
{% block head %}
<meta charset="utf-8"> //这样 在index.html中编码就变成了utf-8
{% endblock %}
三、引用上级代码块在其基础上进行一些修改
{% block 块名 %}
{{ block.super }}
要追加内容
{% endblock %}
追加块内容,例子:
在index.html中
{% extends base.html %}
{% block head %}
{{ block.super }}
<link rel="stylesheet" her="./css.css"> //在index.html中 使用使用gdb编码 ,加载css.css
{% endblock %}
四、加载模板
{% include 块模版 %}
加载模板:例子
在index.html中
{% extends base.html %}
{% block head %}
{{ block.super }}
<link rel="stylesheet" her="./css.css"> //在index.html中 head
{% include "head.html" %}
{% endblock %}
{% include "nav.html" %}
{% include "main.html" %}
{% include "footer.html" %}
五、模块
class mod_name(tornado.web.UIModule):
def render(self):
return self.render_string('modules/模块.html', object=object)
tornado.web.Application(
...
ui_modules={
'模块名': mod_name,
......
}
)
{% model 模块名(object) %}
例子:
在index.html
{
% extends
"main.html"
%
}
{
% block body
%
}
<h2>
Recommended Reading
</h2>
{
% for book in books
%
}
{
% module Book
(book
)
%
}
{
% end
%
}
{
% end
%
}
在app.py中
class
BookModule
(
tornado
.
web
.
UIModule
)
:
def
render
(
self
,
book
)
:
return
self
.
render_string
(
'modules/book.html'
,
book
=
book
)
app
=
tornado
.
web
.
Application
(
handlers
=
[
(
r
'/'
,
HelloHandler
)
]
,
template_path
=
os.path
.
join
(
os.path
.
dirname
(
__file__
)
,
'templates'
)
,
ui_modules
=
{
'Book'
:
Book
Module
}
)
在modules/book.html中
<div
class
=
"book"
>
<h3
class
=
"book_title"
>
{{ book["title"] }}
</h3>
{% if book["subtitle"] != "" %}
<h4
class
=
"book_subtitle"
>
{{ book["subtitle"] }}
</h4>
{% end %}
<img
src
=
"{{ book["image
"] }}"
class
=
"book_image"
/>
<div
class
=
"book_details"
>
<div
class
=
"book_date_released"
>
Released: {{ book["date_released"]}}
</div>
<div
class
=
"book_date_added"
>
Added: {{ locale.format_date(book["date_added"], relative=False) }}
</div>
<h5>
Description:
</h5>
<div
class
=
"book_body"
>
{% raw book["description"] %}
</div>
</div>
</div>
}