web框架--tornado框架之模板引擎
2021-05-14 10:27
阅读:696
YPE html>
标签:styles ado 访问 tle 需要 存放位置 comm 方式 item
使用Tornado实现一个简陋的任务表功能demo来讲解tornado框架模板引擎
一、demo目录结构

二、具体文件内容
2.1、commons.css
.body{ margin: 0; background-color: bisque; }
2.2、index.html
"en">"UTF-8">Title "stylesheet" href=‘{{static_url("commons.css")}}‘/>{{ag}}
{{test_uimethod()}}
{% module MyClass() %}
显示内容
-
{% for item in contents %}
- {{item}} {% end %}
2.3、uimodule.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from tornado.web import UIModule class MyClass(UIModule): def render(self, *args, **kwargs): return ‘UIModule‘
2.4、uimethod.py
#!/usr/bin/env python # -*- coding: utf-8 -*- def test_uimethod(self): return ‘uimethod‘
2.5、index.py
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import tornado.web 4 import tornado.ioloop 5 import uimethod as ut 6 import uimodule as ud 7 8 class IndexHandle(tornado.web.RequestHandler): 9 def get(self, *args, **kwargs): 10 self.render(‘index.html‘, contents=CONTENTS_LIST, ag="") 11 12 def post(self, *args, **kwargs): 13 CONTENTS_LIST.append(self.get_argument(‘name‘)) 14 self.render(‘index.html‘, contents=CONTENTS_LIST, ag=‘this is ag‘) 15 16 if __name__ == ‘__main__‘: 17 CONTENTS_LIST = [] #为存放的是输入框输入的内容 18 #字典表示的是配置文件 19 settings = { 20 ‘template_path‘: ‘template‘, #模板文件的存放位置 21 ‘static_path‘: ‘static‘, #静态文件的存放位置 22 ‘static_url_prefix‘: ‘static/‘, #静态文件前缀,减少每个文件引入都要加前缀的麻烦 23 ‘ui_methods‘: ut, 24 ‘ui_modules‘: ud, 25 } 26 27 application = tornado.web.Application([ 28 (r‘/index‘, IndexHandle) 29 ], **settings) 30 application.listen(80) #设置服务端的监听端口 31 tornado.ioloop.IOLoop.instance().start() #阻塞服务端进程, 等待客户端的访问
2.6、demo运行的效果图

demo详解:
- 模板引擎中的
{{key}}表示取key对应的值, 当key为函数时候执行该函数并取该函数结果. 例如index.html文件中的实际上取得是{{ag}}
index.py的self.render("index.html", ag="this is ag", contents=CONTENTS_LIST)中的参数ag的值 这里执行的是自定义函数, 我们将这个自定义函数写在{{test_uimethod()}}
uimethod.py文件中, 并且在index.py文件中导入, 然后将index.py文件中的settings配置增加一行‘ui_methods‘: ut, 该行内容表示模板引擎可执行自定义函数- 模板引擎中的
{%%}可用于循环语句和条件语言以及自定义类的执行,{% for item in contents %}此处正是用于循环遍历contents中的内容 此处表示模板引擎执行自定义类, 该类的文件对应的是{%module MyClass()%}
uimodule.py文件, 我们需要在index.py的settings中增加一行‘ui_modules‘: ud, 改行表示模板引擎可使用自定义类- 注意, 我们将
index.html文件引入css的方式改为了,static_url()是模板引擎内置的自定义函数, 用该函数引入css文件时候, 仅当css文件内容发生变化时候, 浏览器才会重新缓存该css文件
web框架--tornado框架之模板引擎
标签:styles ado 访问 tle 需要 存放位置 comm 方式 item
原文地址:https://www.cnblogs.com/june-L/p/11992686.html
上一篇:C++幂运算符
下一篇:html DOM操作
评论
亲,登录后才可以留言!