模板引擎

  Tornado中的模板语言和django中类似,模板引擎将模板文件载入内存,然后将数据嵌入其中,最终获取到一个完整的字符串,再将字符串返回给请求者。

  Tornado =的模板支持“控制语句”和“表达语句”,控制语句是使用 {% 和 %} 包起来的 例如 {% if len(items) > 2 %}。表达语句是使用 {{ 和 }} 包起来的,例如 {{ items[0] }}

  控制语句和对应的 Python 语句的格式基本完全相同。我们支持 ifforwhile 和 try,这些语句逻辑结束的位置需要用 {% end %} 做标记。还通过 extends 和 block 语句实现了模板继承。这些在 template 模块 的代码文档中有着详细的描述。

  tornado模 板语言,无论for或者if,结尾都是end,不像django的endfor、endif;另外,tornado模板语言,取数据时跟python一模一样,如下面的取字典里的数据,可以直接dict['key'],也可以dict.get('key','default');不像django里的item.1。

  注:在使用模板前需要在setting中设置模板路径:"template_path" : "tpl"

1.基本使用

import tornado.ioloop
import tornado.web class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html", list_info = [11,22,33],title='Mytitle') application = tornado.web.Application([
(r"/index", MainHandler),
]) if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()

app.py

<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<ul>
{% for item in list_info %}
<li>{{item)}}</li>
{% end %}
</ul>
</body>
</html>

index.html

  表达式可以是任意的Python表达式, 包括函数调用. 模板代码会在包含以下对象 和函数的命名空间中执行 (注意这个列表适用于使用 RequestHandler.render 和 render_string 渲染模板的情况. 如果你直接在 RequestHandler 之外使用 tornado.template 模块, 下面这些很多都不存 在)

在模板中默认提供了一些函数、字段、类以供模板使用:

escape: tornado.escape.xhtml_escape 的別名
xhtml_escape: tornado.escape.xhtml_escape 的別名
url_escape: tornado.escape.url_escape 的別名
json_encode: tornado.escape.json_encode 的別名
squeeze: tornado.escape.squeeze 的別名
linkify: tornado.escape.linkify 的別名
datetime: Python 的 datetime 模组
handler: 当前的 RequestHandler 对象
request: handler.request 的別名
current_user: handler.current_user 的別名
locale: handler.locale 的別名
_: handler.locale.translate 的別名
static_url: for handler.static_url 的別名
xsrf_form_html: handler.xsrf_form_html 的別名

其他方法

2.继承

<html>
<body>
<header>
{% block header %}{% end %}
</header>
<content>
{% block body %}{% end %}
</content>
<footer>
{% block footer %}{% end %}
</footer>
</body>
</html>

layout.html

当我们扩展父模板layout.html时,可以在子模板index.html中引用这些块。

{% extends "layout.html" %}

{% block header %}
<h1>{{ header_text }}</h1>
{% end %} {% block body %}
<p>Hello from the child template!</p>
{% end %} {% block footer %}
<p>{{ footer_text }}</p>
{% end %}

index.html

3、导入(include)

<div>
<ul>
<li>1024</li>
<li>42区</li>
</ul>
</div>

header.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>title</title>
<link href="{{static_url("css/common.css")}}" rel="stylesheet" />
</head>
<body> <div class="pg-header">
{% include 'header.html' %}
</div> <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script> </body>
</html>

index.html

4、自定义UIMethod以UIModule

a. 定义

# uimethods.py

def tab(self):
return 'UIMethod'

uimethods.py

from tornado.web import UIModule
from tornado import escape class custom(UIModule): def render(self, *args, **kwargs):
return escape.xhtml_escape('<h1>hello world</h1>')

uimodules.py

b. 注册

import tornado.ioloop
import tornado.web
from tornado.escape import linkify
import uimodules as md
import uimethods as mt class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html') settings = {
'template_path': 'template',
'static_path': 'static',
'static_url_prefix': '/static/',
'ui_methods': mt,
'ui_modules': md,
} application = tornado.web.Application([
(r"/index", MainHandler),
], **settings) if __name__ == "__main__":
application.listen(8009)
tornado.ioloop.IOLoop.instance().start()

c. 使用

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link href="{{static_url("commons.css")}}" rel="stylesheet" />
</head>
<body>
<h1>hello</h1>
{% module custom(123) %}
{{ tab() }}
</body>

5、模板的自动转义问题

  Tornado默认会自动转义模板中的内容,把标签转换为相应的HTML实体。这样可以防止后端为数据库的网站被恶意脚本攻击。比如,你的网站中有一个评论部分,用户可以在这里添加任何他们想说的文字进行讨论。虽然一些HTML标签在标记和样式冲突时不构成重大威胁(如评论中没有闭<h1>标签),但<script>标签会允许攻击者加载其他的JavaScript文件,打开通向跨站脚本攻击、XSS或漏洞之门。

  所有模板输出默认都会使用 tornado.escape.xhtml_escape 函数转义. 这个行为可以通过传递 autoescape=None 给 Application 或者 tornado.template.Loader 构造器来全局改变, 对于一个模板文件可以使 用 {% autoescape None %} 指令, 对于一个单一表达式可以使用 {% raw ...%} 来代替 {{ ... }}. 此外, 在每个地方一个可选的 转义函数名可以被用来代替 None.

  方法一:是在Application构造函数中传递autoescape=None,另一种方法是在每页的基础上修改自动转义行为,如下所示:

{% autoescape None %}
{{ mailLink }}

这些autoescape块不需要结束标签,并且可以设置xhtml_escape来开启自动转义(默认行为),或None来关闭。

  然而,在理想的情况下,你希望保持自动转义开启以便继续防护你的网站。因此,你可以使用{% raw %}指令来输出不转义的内容。

{% raw mailLink %}

最新文章

  1. malloc calloc realloc,new区别联系以及什么时候用
  2. WCF客户端和服务器时间不一致,导致通道建立失败的问题)
  3. [转] 关于UIView
  4. Oracle通过指令创建用户
  5. perl学习(9) 实例:取出操作时间最长的100个记录
  6. 读取xml并将节点保存到Excal
  7. DRAM的原理设计
  8. 华硕X99-A II 安装使用 志强 XEON E5-1603 v4
  9. Mvc 批量图片上传
  10. 通过spring抽象路由数据源+MyBatis拦截器实现数据库自动读写分离
  11. Docker在Windows下的安装以及Hello World
  12. mysql存储过程的参数名不要跟字段名一样 (血淋淋的代价)
  13. 函数调用前有&quot;::&quot;符号,什么意思啊?
  14. Linux系统分区方案建议
  15. 利用JavaScript计算引擎进行字符串公式运算
  16. (转)linux运维必会MySQL企业面试题
  17. Java学习笔记(3)----网络套接字服务器多线程版本
  18. 常用sql commands以及mysql问题解决日志
  19. 【第一周】c++实现词频统计
  20. IE8下window.open 二次无法加载页面

热门文章

  1. anaconda指定镜像源,解决conda下载速度慢失败问题
  2. 剖析top命令显示的VIRT RES SHR值
  3. yum 安装出错--&quot;Couldn&#39;t resolve host &#39;mirrors.aliyun.com&#39;&quot;
  4. PHP 表格 post 提交 接受
  5. 第二百四十三节,Bootstrap模态框插件
  6. 怎样在xilinx SDK中显示行号
  7. 细节取胜的javadoc
  8. node读写Excel操作
  9. Ubuntu 16.04 LTS sublime text 3 解决不能输入中文
  10. spring 和 struts 整合遇到的问题(学习中)