1. 程式人生 > >Python Flask,Jinja2模板,巨集,macro

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 %}