Python Flask,Jinja2模板,宏,macro

宏类似于python中的函数,宏的作用就是在模板中重复利用代码,避免代码冗余(一次定义,多次使用)。

templates/index.html(模板,定义宏,使用宏):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>宏</title>
</head>
<body>
    
    <!-- 定义宏(不带参数) -->
    {% macro input() %}
        <input type="text" value="" size="30">
    {% endmacro %}

    <h1>input 1</h1>
    <!-- 使用宏(可以多次使用) -->
    {{ input() }}
    
    <hr/>

    
    <!-- 定义宏(带参数) -->
    {% macro input2(type, value, size) %}
        <input type="{{ type }}" value="{{ value }}" size="{{ size }}">
    {% endmacro %}

    <h1>input2</h1>
    <!-- 使用宏 -->
    {{ input2("password", "", 50) }}
    
    <hr/>

    
    <!-- 定义宏(带参数,可以通过等号=为参数指定默认值) -->
    {% macro input3(type="text", value="默认值", size=30) %}
        <input type="{{ type }}" value="{{ value }}" size="{{ size }}">
    {% endmacro %}

    <h1>input3</h1>
    <!-- 使用宏 -->
    {{ input3() }}   <!-- 参数使用缺省的默认值 -->
    {{ input3("password", "", 100) }}   <!-- 可以手动指定参数 -->

    <hr/>
    
    
    <!-- 导入外部文件中定义的宏,并指定别名 -->
    {% import "macro_input.html" as my_input %}
    <h1>input4</h1>
    <!-- 通过别名使用外部导入的宏 -->
    {{ my_input.input4() }}

</body>
</html>

templates/macro_input.html(外部文件中定义的宏):

{% macro input4(type="text", value="", size=30) %}
    <input type="{{type}}" value="{{value}}" size="{{size}}">
{% endmacro %}

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/85465027