flask-模板中的宏

2022-07-27  本文已影响0人  测试探索

一、宏的定义

二、基础使用

app.py

from flask import Flask,render_template,render_template_string,g,url_for

app = Flask(__name__)

@app.route('/macro')
def macro():
    """模板中宏的使用"""
    return render_template('macro.html')
if __name__ == '__main__':
    app.run(debug=True)

macro.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板中宏的使用</title>
    <style type="text/css">
        .input-control{
            border: 1px solid #ff0000;
        }
    </style>
</head>
<body>
    <form action="">
        {% macro input(name,type='text',value = '')%}
            <div>
                <input class = "input-control class2" type = "{{ type }}" name = "{{ name }}" value = "{{ value }}">
            </div>
        {% endmacro %}
        <!-- 用户名 username -->
        {{ input('username',value = "admin") }}
        <!-- 密码 password -->
        {{ input('password',type = "password") }}
        <!-- 年龄age -->
        {{ input('age',type = "number") }}


<!-- 注释的代码,与上面宏的写法表达方式一致
        <div>
            <input class = "input-control class2" type = "text" name = "username" value = "">
        </div>

        <div>
            <input class = "input-control class2" type = "password" name="password">

        </div>
        <div>
            <input class = "input-control class2" type = "number" name="age">
        </div>
-->
    </form>



</body>
</html>

三、文件中宏的使用

image.png
image.png

froms.html

<!--定义宏-->
{% macro input(name,type='text',value = '')%}
    <div>
        <input class = "input-control class2" type = "{{ type }}" name = "{{ name }}" value = "{{ value }}">
    </div>
{% endmacro %}

macro.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板中宏的使用</title>
    <style type="text/css">
        .input-control{
            border: 1px solid #ff0000;
        }
    </style>
</head>
<body>
    <form action="">
        <!-- 引入宏 -->
        {% from 'froms.html' import input %}
        <!-- 用户名 username -->
        {{ input('username',value = "admin") }}
        <!-- 密码 password -->
        {{ input('password',type = "password") }}
        <!-- 年龄age -->
        {{ input('age',type = "number") }}
<!--
        <div>
            <input class = "input-control class2" type = "text" name = "username" value = "">
        </div>

        <div>
            <input class = "input-control class2" type = "password" name="password">

        </div>
        <div>
            <input class = "input-control class2" type = "number" name="age">
        </div>
-->
    </form>

</body>
</html>
image.png
上一篇下一篇

猜你喜欢

热点阅读