flask的宏 macro

1、把它看作jinja2的一个函数,这个函数可以返回一个html字符串

2、目的:代码可以复用,避免代码冗余

定义的两种方式:

1、在模版中直接定义:类似于macro1.html中定义方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>宏的定义</title>
</head>
<body>
{#定义宏#}
{% macro form(action,value='登陆',method='post') %}

    <form action="{{ action }}" method={{ method }}>
        <input type="text" placeholder="用户名" name="username">
        <input type="password" placeholder="密码" name="password">
        <input type="submit" value="{{ value }}">
    </form>

{% endmacro %}

{#调用宏#}
{{ form('/') }}

</body>
</html>

 2、将所有的宏提取到一个模版中macro.html,导入方法:

{% import 'macro.html' as xxx %}

{{ xxx.宏名字(参数) }}

macro/macro.html 定义宏的模版

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>宏的定义</title>
</head>
<body>
{#定义宏#}
{% macro form(action,value='登陆',method='post') %}

    <form action="{{ action }}" method={{ method }}>
        <input type="text" placeholder="用户名" name="username">
        <input type="password" placeholder="密码" name="password">
        <input type="submit" value="{{ value }}">
    </form>

{% endmacro %}

</body>
</html>

macro/macro2.html 调用宏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>宏的使用2</title>
</head>
<body>
{% import 'macro/macro.html' as macro with context %}
{{ macro.form('/',value='注册') }}
</body>
</html>

 3、声明变量的方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>宏的使用2</title>
</head>
<body>

{% set username = 'zhansan' %}
{{ username }}

{% with num=1000  %}
    {{ num }}
{% endwith %}

</body>
</html>

总结:

变量:{{ 变量 }}

块:

{% if 条件 %}......{% endif %}

{% for 条件 %}......{% endfor %}

{% block 条件 %}......{% endblock %}

{% macro 条件 %}......{% endmacro %}

 

{% include '' %} 包含

{% import '' %} 导入宏

{% extends '' %} 模版继承

 

{{ url_for('static',filename=' ')}} 导入静态文件

{{ macro_name(xxx) }} 调用宏

view:

@app.route('/',endpoint='',methods=['GET','POST'])

def index():

    直接使用request

    return response| ' ' |render_template('xxx.html')

template:

   模版语法

 

posted @ 2021-09-14 11:39  fat_girl_spring  阅读(118)  评论(0编辑  收藏  举报