20.Tornado_使用模板的方式

1.概述

网站如何向客户端返回一个漂亮的页面?就是通过使用模板的方式

2.模板使用方式

  1. 通过字符串返回
  2. 通过模板Template返回(分为直接返回内容与传递参数返回)
  3. 通过模板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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想成为数据分析师的开发工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值