《Introduction to Tornado》笔记04-tornado框架模板的操作-模板渲染+模板继承+静态文件与模板文件目录配置
简单的模板操作见这篇博客
模板继承与静态文件的引用等综合的例子看这个 *****
目录结构如下
—— static目录存放静态的css与js文件
——templates目录存放程序的模板文件:base.html是母版文件,index.html继承自这个母版文件
—— app.py是tornado的启动文件
模板文件如下
base.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ page_title }}</title> <link rel="stylesheet" href="{{ static_url('css/style.css') }}" /> </head> <body> <div id="container"> <header> {% block header %}<h1>Burt's Books</h1>{% end %} </header> <div id="main"> <div id="content"> {% block body %}{% end %} </div> </div> <footer> {% block footer %} <p> For more information about our selection, hours or events, please email us at <a href="mailto:contact@burtsbooks.com">contact@burtsbooks.com</a>. </p> {% end %} </footer> </div> <script src="{{ static_url('js/script.js') }}"></script> </body> </html>
index.html
{% extends "base.html" %} {% block header %} <h1>{{ header_text }}</h1> {% end %} {% block body %} <div id="hello"> <p>Welcome to Burt's Books!</p> <p>...</p> </div> {% end %}
app.py文件如下
import tornado.web import tornado.httpserver import tornado.ioloop import tornado.options import os.path from tornado.options import define, options define("port", default=8014, help="run on the given port", type=int) class MainHandler(tornado.web.RequestHandler): def get(self): self.render( "index.html", page_title="Burt's Books | Home", header_text="Welcome to Burt's Books!", ) class Application(tornado.web.Application): def __init__(self): handlers = [ (r"/", MainHandler), ] settings = dict( template_path=os.path.join(os.path.dirname(__file__),"templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), debug=True, ) # 执行父类中的__init__方法,super或者下面的方法 super().__init__(handlers,**settings) # tornado.web.Application.__init__(self, handlers, **settings) if __name__ == "__main__": # 命令行方式启动tornado程序 tornado.options.parse_command_line() # 讲Application类实例化的对象传进去 http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
~~~