美文网首页
Tornado框架的模板继承(四)

Tornado框架的模板继承(四)

作者: 梦捷者 | 来源:发表于2020-04-15 08:50 被阅读0次

一、模板的继承

1、extends
{% extends filename %}继承模板,在子模板中会把父模板的所有内容都继承到子模板中,减少大量重复代码。
2、block
{% block name %}...{% end %}
在父模板中被词语句包裹的代码块在子模板中可以被重写,覆盖父模板中的语句。

3、示例

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}Torando{% end %}</title>
    <link rel="shortcut icon" href="{{ static_url('images/hu.ico')}}"/>
</head>
<body>
{% block body %}
<br>
{% if username != 'no' %}
欢迎{{username}}!!!</br>
{% else %}
请登录
{% end %}
是第{{num}}号
{% end %}
</body>
</html>

3extends.html

{% extends base.html %}
{% block title %}
Extend the father band
{% end %}
{% block body %}
<h1>继承父模板的子模板</h1>
{% if username != 'no' %}<br>
欢迎<b>{{username}}</b>!!!</br>
{% else %}
请登录
{% end %}

<img src="{{ static_url('images/1.jpg') }}" width="250" height="250"/>
<br>
{% include 4static_modle.html %}
{% end %}

二、模板文件的导入

1、include标签可以导入模板文件,但是导入的模板中不要再出现 extends 和 block两个标签。
2、include
{% include filename%}(注意:在django中filename加单引号
include 可以导入一些其他的模板文件,一般使用 include 的时候,模板文件中不使用 block 块 。
3、静态文件的示例
导入用法在3extends.html中
4static_modle.html

<font style="color:yellow">我是静态文件哈!!!!</font>

三、函数和类的导入(导入到相应的模板中)

1、渲染html文件时导入(在 Handler 中渲染模板时传入)

class Calculation():
    def sum(self, a, b):
        return a+b


class ExtendsHandler(tornado.web.RequestHandler):
    def get(self):
        username ='小明'
        self.render('3extends.html', username=username, hu=self.hu, Calculation=Calculation)#导入的类和方法为Calculation和hu方法

    def hu(self):
        return 'this is class and way be transfered by the modle'
{% extends base.html %}
{% block title %}
Extend the father band
{% end %}
{% block body %}
<h1>继承父模板的子模板</h1>
{% if username != 'no' %}<br>
欢迎<b>{{username}}</b>!!!</br>
{% else %}
请登录
{% end %}

<img src="{{ static_url('images/1.jpg') }}" width="250" height="250"/>
<br>
{% include 4static_modle.html %}
<br>
{{ hu() }}
<br>
{% set c=Calculation() %}
数字的和为<b>{{ c.sum(5 ,8) }}。</b>
{% end %}

2、模板中直接导入

  • 导入内置模块(直接在子模块中进行)
{% import time %}
{{ time.time() }}
  • 导入自定义模块
    自定义模块的文件内容:mod_file.py
class Calculation1:
    def sum(self, a, b):
        return a+b


def add(a, b):
    return a+b


def upper(s):
    return s.upper()


导入自定义模块(在子模块中进行渲染)

{% from mod_file import Calculation1,upper,add %}
{% set s=Calculation1() %}
导入自定义模块的和为{{ s.sum(5,6) }}<br>
{{ upper('this a bird') }}<br>
导入自定义模块方法的和{{ add(4,7) }}

注意:python解释器查找 mod_file 时是根据 py 文件的路径来查找的,不是根据模板的路径来查找

  • 应用自定义模块中的方法
    以上面的自定义mod_file.py模块为基准
{% apply upper %}
{% include 4static_modle.html %} #小写变为大写
{% end %}

用apply语句,使用函数的作用范围到最近的{%end%}为止。

四、ui_methods和ui_modules的应用(进行复用效果)

参考文档:https://tornado-zh.readthedocs.io/zh/latest/guide/templates.html

1、第一步

  • 新建文件ui_methods.py
    新建文件ui_methods.py ,这里的文件名是随意的只要在import时合法即可,这里可以新建一个文件夹,如utils,来放置 ui_methods.py 和 ui_modules.py
def methods1(self):  #注意这里要加上self 
    return 'ui_methods 1' 
def methods2(self): 
    return 'ui_methods 2'
  • 新建文件ui_modules.py
    新建文件ui_modules.py,使用ui_modules需要继承UIModule类
from tornado.web import UIModule
class UiModule(UIModule):
    def render(self, *args, **kwargs):
        return '我是 ui_module'

2、第二步
在项目中导入import utils.ui_modules和import utils.ui_methods,是在app_demo.py(启动tornado项目的文件夹下)

3、第三步
配置 Application 参数

可以写成
ui_methods=utils.ui_methods,
ui_modules=utils.ui_modules,
也可以写成字典形式:
ui_modules={
'UiModule':utils.ui_modules.UiModule,
}
import random
import time
import datetime
import tornado.web
import tornado.ioloop
from tornado.options import options, define, parse_command_line
import utils.ui_methods
import utils.ui_modules

define('port', default=8080,help="运行端口")


class FirstHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("<h1><span style='color:red'>这是首页面</span></h1>")


class PictureHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("<html><body><img src='/static/images/1.jpg'></body></html>")
        #这里satic前面加上/(正斜杆)是代表绝对路径,如果不加,则代表相对路径,但是在多个路由的时候就会报错。

    def initialize(self):
        print('对象{}被创建了'.format(self))


class TemplateHandler(tornado.web.RequestHandler):
    def get(self):
        username = '小龙'
        items = ["Item 1", "Item 2", "Item 3"]
        line = "====="*6
        time_now = time.time()
        atga = "<a href='http://www.baidu.com' target='_blank'>_百度_</a><br>"
        student_list = [
            {'name': '小红', 'age': 18, 'hobby': '打篮球', 'web': 'http://www.baidu.com'},
            {'name': '小明', 'age': 16, 'hobby': '打篮球', 'web': 'http://www.jianshu.com'},
            {'name': '小浩', 'age': 20, 'hobby': '打羽毛球', 'web': 'http://www.baidu.com'},
        ]
        self.render('1demo.html', username=username, title="基础模板", items=items, students=student_list, line=line, time=time_now, atga=atga)

    def post(self):
        username = self.get_argument('name', 'no')
        number = int(random.random()*100 + 1)
        self.render('2demo.html', username=username, num=number)


class Calculation():
    def sum(self, a, b):
        return a+b


class ExtendsHandler(tornado.web.RequestHandler):
    def get(self):
        username ='小明'
        self.render('3extends.html', username=username, hu=self.hu, Calculation=Calculation)

    def hu(self):
        return 'this is class and way be transfered by the modle'


def make_app():
    handlers = [
        (r'/', FirstHandler),
        (r'/picture', PictureHandler),
        (r'/template', TemplateHandler),
        (r'/extends', ExtendsHandler)
    ]
    settings = \
        {'debug': True,
         'static_path': 'static',
         'template_path': 'templates',
         'ui_methods': utils.ui_methods,
         'ui_modules': utils.ui_modules
         }#直接写staic这里是相对路径,这是相对与这个脚本的路径而言的
    app = tornado.web.Application(handlers=handlers, **settings)
    return app


if __name__ == '__main__':
    app = make_app()
    # app.listen(8000)
    parse_command_line()
    port_new = options.port
    app.listen(port_new)
    print(type(port_new))
    print("Tornado server running at %s port" % port_new)
    tornado.ioloop.IOLoop.current().start()


4、第四步
在所有相应模板中调用

<br>{% module UiModule() %}
<br>{{ methods1() }}<br>

5、其他方法
linkify

<br>{%raw linkify('百度: http://www.baidu.com') %}<br>

linkify生成一个链接,但是要注意模板转义

相关文章

网友评论

      本文标题:Tornado框架的模板继承(四)

      本文链接:https://www.haomeiwen.com/subject/uzsquctx.html