Flask框架模板中的宏的定义与使用(十五)

使用% macro 函数名() %}{% endmacro %}标签来定义宏

一、宏定义在模板内部的使用

1、不传参数的宏的定义与使用
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单界面</title>
</head>
<body>
{% macro textarea() %}
     <textarea name="text"></textarea>
    <input type="submit" value="提交">
{% endmacro %}
<form method="post">
   {{ textarea() }}
</form>
</body>
</html>
2、传参数的宏的定义与使用
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单界面</title>
</head>
<body>
{% macro text(type, value, name) %}
    <input type="{{ type }}" value="{{ value }}" name="{{ name }}">
{% endmacro %}
<form method="post">
   {{ text('text','名字','名字') }}
</form>

{% macro text1(type="text", value="你好", name="你好") %}
    <input type="{{ type }}" value="{{ value }}" name="{{ name }}">
{% endmacro %}
<form method="post">
   {{ text1() }}
</form>
</body>
</html>

二、宏定义在外部的使用

imported_macro_page.html内容

{% macro text1(type="text", value="你好", name="你好") %}
  <input type="{{ type }}" value="{{ value }}" name="{{ name }}">
{% endmacro %}

以下是导入外部的宏模板并且取别名使用函数进行构造

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>宏定义在外部的使用</title>
</head>
<body>
{% import "HomePage/imported_macro_page.html" as hu %}
{{ hu.text1() }}
</body>
</html>
发布了21 篇原创文章 · 获赞 0 · 访问量 121

猜你喜欢

转载自blog.csdn.net/qq_41706810/article/details/105737963