# coding=utf-8 import os BASE_DIRS = os.path.dirname(__file__) # 参数 options = { “post” : 8000, } # 配置 settings = { "static_path" : os.path.join(BASE_DIRS,"static"), "template_path":os.path.join(BASE_DIRS,"templates"), "debug":True, }
# coding = utf-8 import tornado.web from views import views import config class Application(tornado.web.Application): def __init__(self): app = [ (r"/home",views.HomeHandler), ] super(Application, self).__init__(app, **config.settings)
# coding = utf-8 # 视图 from tornado.web import RequestHandler class HomeHandler(RequestHandler): def get(self, *args, **kwargs):
temp = 100
per = {"name" : "hello", "age":18} self.render("home.html", num = temp, per = per)
# 方法2
self.render("home.html", num = temp, **per)
<html lang="en"> <head> <meta charset="UTF-8"> <title>主页</title> </head> <body> <h1>这里是home页面</h1> <h1>num: {{ num }}</h1>
<h1>per["name"]</h1>
<h1>{{name}}</h1> </body> </html>
# 把函数当参数传递
class FuncHandler(RequestHandler): def get(self, *args, **kwargs): def mySum(n1,n2): return n1+n2 self.render(‘home.html’,mysum = mySum)
# 在 home.html 中使用
<h1>{{ mysum(100,99) }}</h1>
咱们能够经过raw语句来输出不被转义的原始格式,如:css
{% raw text %}
注意: 只能关闭一行;在Firefox浏览器中会直接弹出alert窗口,而在Chrome浏览器中,须要set_header("X-XSS-Protection", 0)html
若要关闭自动转义:web
一种方法是在Application构造函数中传递autoescape=Noneexpress
另外一种方法是在每页模板中修改自动转义行为,添加以下语句:浏览器
{% autoescape None %}
escape()缓存
关闭自动转义后,能够使用escape()函数来对特定变量进行转义,如:app
{{ escape(text) }}
咱们能够使用块来复用模板,块语法以下:函数
{% block block_name %} {% end %}
而子模板index.html使用extends来使用父模板base.html,以下:tornado
{% extends "base.html" %}
(r"/(.*)$", tornado.web.StaticFileHandler,{“path”:os.path.join(config.BASE_DIRS,"static/html"),
"default_filename":"index.html"})