Flask_day03

模板代码的复用 ( 宏( Macro )、继承( Block )、包含( include ) 均能实现代码的复用 )

二、宏: 宏(Macro)的功能类似函数,可以传入参数,需要定义、调用。

 1 {% macro input(label='', type='text', value='', name='') %}
 2 <label>{{ label }}</label><input type="{{ type }}" name="{{ name }}"><br/>
 3 {% endmacro %}
 4 
 5 
 6 <form>
 7     {{ input('用户名:', name='username') }}
 8     {{ input('密码:',type='password', name='password') }}
 9     {{ input('确认密码:',type='password2', name='password2') }}
10     {{ input(type='submit', value='注册') }}
11 
12 </form>
View Code

  为了重复使用宏,可以将其保存在单独的文件中,然后在需要使用的模板中导入,再调用:

1 {% import 'macro.html' as func %}
2 
3 <form>
4     {{ func.input('用户名:', name='username') }}
5     {{ func.input('密码:',type='password', name='password') }}
6     {{ func.input('确认密码:',type='password', name='password2') }}
7     {{ func.input(type='submit', value='注册') }}
8 
9 </form>
View Code

二、继承: 继承(Block)的本质是代码替换,一般用来实现多个页面中重复不变的区域。

  首先,创建一个名为base.html 的基模板:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8" />
 5     <title>Document</title>
 6 </head>
 7 <body>
 8     {% block top %}
 9         顶部内容
10     {% endblock top %}
11 
12     {% block content %}
13         中间内容
14     {% endblock content %}
15 
16     {% block bottom %}
17         底部内容
18     {% endblock bottom %}
19 </body>
20 </html>
View Code

  下面是子模板:

1 {% extends 'base.html' %}
2 
3 {% block content %}
4     {{ super() }}
5     需要填充的内容
6 {% endblock content %}
View Code

三、包含: 包含(include)是直接将目标模板文件整个渲染出来。

创建一个名为 include.html 的基模板,然后就可以在其它的文件中使用了:

1 {% include 'common.html' ignore missing %}
2 {# 如文件不存在,加上 ignore missing 关键字,程序就不会报异常 #}
View Code

模板中特有的变量和函数

    config:{{ config.DEBUG }}

请求上下文中两个变量:
    当前路由路由:{{ request.url }}
    session取值 {{ session.name }}

应用上下文中1个变量:
    g变量:{{ g.name }}

两个直接可以使用的函数:
    <a href="{{ url_for('index') }}">回到首页</a><br/>

    获取闪现消息:
    {% for message in get_flashed_messages() %}
        {{ message }}
    {% endfor %

  

猜你喜欢

转载自www.cnblogs.com/W-Zing/p/9553597.html