您好,欢迎访问一九零五行业门户网

tornado总结4-html模板使用2_html/css_WEB-ITnose

参考地址
http://www.tornadoweb.org/en/stable/guide/templates.html?highlight=render#ui-modules
目的说明   osc的所有页面顶部都有这个导航条, 我们可以使用tornado的ui modules来实现导航条,实现代码的复用.
代码结构
增加了一个my_uimodules.py,里面包含了供tornado模板使用的uimodules,增加了一个header.html里面是导航条的html代码,增加了一个page2.py,返回简单的html页面page2.html.
实际运行效果 访问路径 /时的效果
点击导航链接  页面1的效果
点击导航链接  页面2的效果
代码说明   my_uimodules.py import tornado.webclass headerbar(tornado.web.uimodule): def render(self, location): return self.render_string(header.html, location=location)class headerbar2(tornado.web.uimodule): def render(self, location): return self.render_string(header.html, location=location)
所有的模板驱动都继承自 tornado.web.uimodule , 然后调用render_string调用指定的模板和参数. 你可以在此处写一个顶部导航栏再写个侧边导航栏. 我只在这里写了一个顶部导航模板驱动. 它接受一个参数location, 我把它作为导航栏最右侧的页面说明. 本模板驱动返回的是header.html,并把location传给了它.
header.html 主页 页面1 页面2 你现在处于页面 {{ location }}

本模板文件作为页面的顶部导航栏,并通过location参数得到当前的页面地址
main.py import osimport tornado.httpserverimport tornado.ioloopimport tornado.webimport my_uimodulesfrom handlers.home import homehandlerfrom handlers.page1 import page1handlerfrom handlers.page2 import page2handlerclass pagenotfoundhandler(tornado.web.requesthandler): def get(self): return self.write_error(404)class application(tornado.web.application): def __init__(self): handlers = [ (r/, tornado.web.redirecthandler, {url: /home}), (r/home, homehandler), (r/page1, page1handler), (r/page2, page2handler), (r.*, pagenotfoundhandler), ] settings = dict( static_path= os.path.join(os.path.dirname(__file__), static), template_path=os.path.join(os.path.dirname(__file__), templates), ui_modules=my_uimodules, ) tornado.web.application.__init__(self, handlers, **settings)if __name__ == __main__: port = 8899 application = application() http_server = tornado.httpserver.httpserver(application, xheaders=true) http_server.listen(port) print('listen on http://localhost:{0}'.format(port)) print('listen on http://localhost:{0}/page1'.format(port)) print('listen on http://localhost:{0}/page2'.format(port)) tornado.ioloop.ioloop.instance().start()
在torndao进行初始化设置时, 在settings 里面指定了自定义模板所在模块.
ui_modules=my_uimodules
当tornado在处理模板时,如果碰到如下的语句, 它就会去刚才设置的ui_modules模块中去找 xxxx模板驱动
{% module xxxx %}
页面代码 home.html
主页 {% module headerbar(主页) %} 这是主页
page1.html
{{ argu1 }} {% module headerbar(页面1) %} 这是page1 {% for i in argu2 %} {{ i }} {% end %}
page2.html
page2 {% module headerbar(页面2) %} 这是page2
所有页面模板的body的第一行都添加了一个 {% module headerbar(页面2) %} ,如前面所讲当tornado在处理render的模板时如果碰到了这种格式的请求,就会去 ui_modules 指定的模块my_uimodules下面查找headerbar,并把页面2作为第一个参数传给了它, headerbar把这个参数当做location传给了 header.html.  
    就这样每个页面顶部导航栏的相同和不同之处都体现了出来.
代码git地址  
http://git.oschina.net/donggen/tornado-test
其它类似信息

推荐信息