PYTHON 八月 13, 2019

第4节、模板引擎02

文章字数 13k 阅读约需 12 mins. 阅读次数 1000000

一、macro 宏的使用

概述: 类似于python中的函数

(1)主体结构

{ % macro 宏名称([参数...]) % }
    ...
{ % endmacro % }
{{ 宏名称([参数...]) }}

实例

{ % macro form(textname,text='text',name='',value='') % }
    <p>{{ textname }}<input type="{{ text }}" name="{{ name }}" value="{{ value }}"></p>
{ % endmacro % }

<form action="">
    {{ form('用户名:',name='username') }}
    {{ form('密码:','password','userpass') }}
    {{ form('','submit',value='submit') }}
</form>

(2)导入macro

common/public_macro.html

  • from … import … as ..
{ % from 'common/public_macro.html' import form % }
{ % from 'common/public_macro.html' import form as f % } #起别名f
  • import … as
{ % import 'common/public_macro.html' as mymacro % }

注意:

  1. 宏的调用 必须在定义的下方来调用
  2. 如果有形参且没有默认值则可以不传实参
  3. 参数默认从左到右依次对应
  4. 形参默认值 遵循默认值规则 (有默认值的放在右侧)
  5. 关键字参数的使用 一样
  6. 当导入的包名字过长,或者是当前文件中存在同名的变量或者函数,类名 为防止重名覆盖 使用 as 起别名

二、模板继承

1. extends

格式:{ % extends ‘模板路径/模板名称.html’ % }

2. block

对于父模板的代码的替换

实例

base.html(父模板)

<!DOCTYPE html>
<html lang="en">
<head>
    { % block head % }
    <meta charset="UTF-8">
    { % block meta % }
    { % endblock % }

    <title>{ % block title % }base{ % endblock % }</title>
    <style>
        { % block style % }
            header,footer{
                width:100%;
                height:40px;
                border:1px solid #000;
                background-color: #000;
                color: #fff;
            }
            div{
                width:100%;
                height:400px;
                background-color: red;
            }
        { % endblock % }
    </style>

    { % block link % }

    { % endblock % }
    { % block script % }

    { % endblock % }
    { % endblock % }
</head>
<body>
<header>导航</header>
<div>
    { % block con % }
    { % endblock % }
</div>
<footer>底部栏</footer>
</body>
</html>

child.html(子模板)

{ % extends 'common/base.html' % }
{ % block title % }
child
{ % endblock % }
{ % block style % }
    { { super() } }
    a{display:block;width:200px;height:200px;color:white;background-color:yellow;}
    a:hover{background-color:blue;}
    div{background-color:green;}
{ % endblock % }
{ % block con % }
    我是子模板的内容部分
    <a href="">点击去百度</a>
{ % endblock % }

注意: 如果子模板继承了父模板后代码缺失或者样式不起作用,查看是否调用了{ { super () } },super调用父模板中被替换掉的代码和样式

三、在flask中使用bootstrap(flask-bootstrap)

(1)创建bootstrap模板对象

from flask_bootstrap import Bootstrap
app.config['BOOTSTRAP_SERVE_LOCAL'] = True #加载本地的bootstrap样式 否则从网络请求
bootstrap = Bootstrap(app)

(2)使用flask-bootstrap的base模板

{ % block doc -% }
<!DOCTYPE html>
<html{ % block html_attribs % }{ % endblock html_attribs % }>
{ %- block html % }
  <head>
    { %- block head % }
    <title>{ % block title % }{{title|default}}{ % endblock title % }</title>

    { %- block metas % }
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    { %- endblock metas % }

    { %- block styles % }
    <!-- Bootstrap -->
    <link href="{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet">
    { %- endblock styles % }
    { %- endblock head % }
  </head>
  <body{ % block body_attribs % }{ % endblock body_attribs % }>
    { % block body -% }
    { % block navbar % }
    { %- endblock navbar % }
    { % block content -% }
    { %- endblock content % }

    { % block scripts % }
    <script src="{{bootstrap_find_resource('jquery.js', cdn='jquery')}}"></script>
    <script src="{{bootstrap_find_resource('js/bootstrap.js', cdn='bootstrap')}}"></script>
    { %- endblock scripts % }
    { %- endblock body % }
  </body>
{ %- endblock html % }
</html>
{ % endblock doc -% }

(3)自定义base 继承flask-bootstrap的base

实例: 引用bootstrap的导航栏

{ % extends 'bootstrap/base.html' % }
{ % block navbar % }
    <nav class="navbar navbar-inverse" style="border-radius: 0px;">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                        data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#"><span class="glyphicon glyphicon-fire" aria-hidden="true"></span></a>
            </div>
            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">首页<span class="sr-only">(current)</span></a></li>
                    <li><a href="#">发表博客</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                    <form class="navbar-form navbar-left">
                        <div class="form-group">
                            <input type="text" class="form-control" placeholder="Search">
                        </div>
                        <button type="submit" class="btn btn-default">Submit</button>
                    </form>
                    <li><a href="#">欢迎:...</a></li>
                    <li><a href="#">登录</a></li>
                    <li><a href="#">注册</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                           aria-expanded="false">个人中心<span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Action</a></li>
                            <li><a href="#">Another action</a></li>
                            <li><a href="#">Something else here</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>
{ % endblock % }
{ % block content % }
<div class="container">
  { % block pagecontent % }
    就是主体内容
  { % endblock % }
</div>
{ % endblock % }

(4)子模板继承自定义的base模板

{ % extends 'common/base.html' % }
{ % block title % }
首页
{ % endblock % }
{ % block pagecontent % }
<h1>首页</h1>
{ % endblock % }

继承过程:

子模板—–继承—–>自定义的base —–继承—->flask-bootstrap的base模板

四、自定义错误模板

manage.py


#捕获404
@app.errorhandler(404)
def page_not_found(e):
    return render_template('error/error.html',title='404 NOT_FOUND',h1con='404页面找不到...',error=e)
#捕获500
@app.errorhandler(500)
def server_error(e):
    return render_template('error/error.html',title='500 SERVER_ERROR',h1con='当前服务繁忙 请稍后再次访问...')

error/error.html

{ % extends 'common/base.html' % }
{ % block title % }
{{ title }}
{ % endblock % }
{ % block pagecontent % }
    <h1>{{ h1con }}</h1>
    { % if error % }
        <div class="alert alert-danger" role="alert">{{ error }}</div>
    { % endif % }
{ % endblock % }

五、静态文件加载

概述: 上传文件,比如网站用到的图片,视频,音频,js,css…

目录结构

project/
    templates/ #模板目录
    static/  #静态资源目录
        img/
        js/
        css/
        upload/
    manage.py

加载静态资源

实例: 设置页面图标

{ % extends 'common/base.html' % }
{ % block title % }
首页
{ % endblock % }
{ % block head % }
    { { super () } }
    <link rel="icon" href="{{ url_for('static',filename='img/timg.jpeg',_external=True) }}">
{ % endblock % }
{ % block pagecontent % }
<h1>首页</h1>
<img src="{{ url_for('static',filename='img/timg.jpeg') }}" alt="">
<link rel="stylesheet" href="{{ url_for('static',filname='css/index.css') }}">
{ % endblock % }

注意:

  • static视图函数是flask为我们提供的,作用是构造出到static静态文件夹的路径,想加载哪个文件就使用参数filename=’路径/文件名称’
  • _external=True 显示绝对路径
{{ url_for('static',filename='img/timg.jpeg',_external=True) }}

六、视图函数传递参数到模板的方法

(1) 直接在render_template()中传递

@app.route('/')
def index():
    return render_template('index.html',title='title',....)

(2) 通过字典的方式

@app.route('/')
def index():
    return render_template('index.html',data={'title':'title',....})

模板中调用

{{ data.title }} 

(3) 使用 locals() 函数

@app.route('/test/')
def test():
    name = '张三'
    age = 18
    print(locals())
    return render_template('index.html',**locals()) #将字典变成关键字参数

模板中使用

{{ name }}
{{ age }}

上一篇:
下一篇:
0%