# 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"})