目录
1、templates下新建macro文件夹,再新增macro1.html
1、实际应用宏会单独设置再一个文件,接上例,在templates/macro下新增macro.html
2、在templates/macro下新增macro2.html
macro
1、把他看作是jinja2的一个函数,这个函数可以返回一个html字符串
2、目的:代码可以复用,避免代码冗余
宏定义有两种方式:
方式一、简单示例
1、templates下新建macro文件夹,再新增macro1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>宏的定义</title>
</head>
<body>
<!-- action,value='登录',method='post' 参数化,提供默认值-->
{% macro form(action,value='登录',method='post') %}
<form action="{{ action }}" method={{method}}>
<input type="text" placeholder="用户名" name="username">
<br>
<input type="text" placeholder="密码" name="password">
<br>
<input type="submit" value="{{ value }}">
</form>
{% endmacro %}
{# 调用宏 #}
{{ form('/') }}
</body>
</html>
2、app.py新增路由
@app.route('/macro1')
def use_macro():
return render_template('macro/macro1.html')
3、启动服务
方式二、实际应用示例
1、实际应用宏会单独设置再一个文件,接上例,在templates/macro下新增macro.html
<!-- action,value='登录',method='post' 参数化,提供默认值-->
<!-- 宏全局设置,单独配置文件进行编码 -->
{% macro form(action,value='登录',method='post') %}
<form action="{{ action }}" method={{method}}>
<input type="text" placeholder="用户名" name="username">
<br>
<input type="text" placeholder="密码" name="password">
<br>
<input type="submit" value="{{ value }}">
</form>
{% endmacro %}
2、在templates/macro下新增macro2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>宏的调用,使用模板</title>
</head>
<body>
{% import 'macro/macro.html' as f %}
{{ f.form('/welcome',value='注册') }}
</body>
</html>
3、app.py新增路由
@app.route('/macro2')
def use_macro2():
return render_template('macro/macro2.html')