1.概述
网站如何向客户端返回一个漂亮的页面?就是通过使用模板的方式
2.模板使用方式
- 通过字符串返回
- 通过模板Template返回(分为直接返回内容与传递参数返回)
- 通过模板render返回()
3.测试以上方法的代码展示
from tornado import web,ioloop, template
from tornado.web import RequestHandler
# 方式1: 通过字符串返回
class IndexHandler1(RequestHandler):
def get(self):
args = 'Template的使用1'
self.write(f'<h1>Hello Tornado{args}</h1>')
# 方式2: Template 直接返回内容
class IndexHandler2(RequestHandler):
def get(self):
args = 'Template的使用2'
t = template.Template(f'<h1>Hello Tornado{args}</h1>')
self.write(t.generate())
# 方式3: Template 传递参数返回
class IndexHandler3(RequestHandler):
def get(self):
a = 'Template的使用3'
t = template.Template('<h1>Hello Tornado{{args}}</h1>')
self.write(t.generate(args = a))
# 方式4: Loader直接返回模板文件
class IndexHandler4(RequestHandler):
def get(self):
a = 'Template的使用4'
loader = template.Loader('./templates/')
self.write(loader.load('index12_1.html').generate(args = a))
# Loader直接返回模板文件,这个默认会在项目文件根目录查找文件,
# 如果需要修改去在Application中设置template_path
class IndexHandler5(RequestHandler):
def get(self):
a = 'Template的使用5'
self.render('index12_1.html', args = a)
if __name__ == '__main__':
app = web.Application([
('/index1/?',IndexHandler1),
('/index2/?',IndexHandler2),
('/index3/?',IndexHandler3),
('/index4/?',IndexHandler4),
('/index5/?',IndexHandler5)
],
debug=True, template_path = './templates/') # 设置查找路径
app.listen(8000)
ioloop.IOLoop.current().start()