模板继承和UImethod、UImodules

模板继承与引用

主文件05-extendes.py文件:

class MainHandler(RequestHandler):
    def get(self):
        name = self.get_argument('name','')
        self.render('04-extend.html',username = name)

application = tornado.web.Application(
    handlers=[
        (r'/',MainHandler),
    ],
    debug=True,
    template_path = 'templates',
    static_path='static',
    autoescape = None, #全局取消转义
)

render返回的文件04-extend.html

extends

{% extend *filename* %}继承模板,在子模板中会把父模板的所有内容都继承到子模板中,减少大量重复代码

block

{% block *name* %}...{% end %}  被词语句包裹的代码块在子模板中可以被重写,覆盖父模板中的

{% extends ./03-base.html %}
{% block title %} Extend {% end %}
{% block body %}
{% include ./05-include.html %}
 <h1> hello world!</h1>
{% end %}
{% block image %}
<img src="{{ static_url('images/01.jpg') }}" alt="">

{% end %}

继承自基类文件 03-base.html

<head>
    <meta charset="UTF-8">
    <title> {% block title %}Tornado{% end %}</title>
</head>
<body>
    {% block body %}
    <h1>taka</h1>
    <h1>gulu</h1>
        {% end %}
    <h1>litao</h1>
    {% block image %} {% end %}

</body>

include 引用自05-include.html

{% include *filename*%} include 可以导入一些其他的模板文件,一般使用 include 的时候,模板文件中不使用 block 块

{% if username !='' %}
    欢迎 {{ username }} 登录
<img src="static/images/01.jpg" width="200px" alt="">
<img src="{{ static_url('images/02.webp') }}" width="200px" alt="">
{% else %}
    亲,请登录
{% end %}

函数跟类导入

1. 渲染时导入

import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
from tornado.web import RequestHandler
from tornado.options import define,options
import time

define('port',default=8080,help='run server',type=int)

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

class MainHandler(RequestHandler):
    def haha(self):
        return 'this is haha function'
    def get(self):
        name = self.get_argument('name','')
        self.render('04-extend.html',
                    username = name,
                    haha = self.haha,   #函数导入
                    heihei = HeiHei()   #类的实例导入
                    )

application = tornado.web.Application(
    handlers=[
        (r'/',MainHandler),
    ],
    debug=True,
    template_path = 'templates',
    static_path='static',
)

2.模板中直接导入

2.1 导入内置模块

2.2 导入自定义模块

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

{% block body %}
{% include ./05-include.html %}
 <h1> hello world!</h1>
{{ haha() }}  #渲染时导入
<br>
{{ heihei }}   #渲染时导入
<br>
{{ heihei.sum(2,3) }}  #渲染时导入
<br>
{% import time %}   #模板中直接导入
{{ time.ctime() }}
<br>
{% from util.mod_file import add_num %}  #导入自定义模块
{{ add_num(1,11) }}
{% end %}

3.ui_methods跟ui_modules

猜你喜欢

转载自www.cnblogs.com/taoge188/p/10630967.html