1、宏的使用
模板中的宏跟python中的函数类似,可以传递参数,但是不能有返回值。
可以将一些经常用到的代码片段放到宏中,然后把一些不固定的值抽取出来当成一个变量。
提示:
- 实际开发中,不会把宏在一个页面内定义 并直接使用
- 一般把宏定义放到一个专门的文件夹中,方便进行统一管理
- 之后,哪一个页面需要使用某个宏,需要导入宏才能使用
示例代码:
main.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>宏的使用</title>
</head>
{% macro inp(type,name="",value="") %}
<input type="{{type}}" name="{{name}}" value="{{value}}">
{% endmacro %}
<body>
<h1>宏的使用</h1>
<table>
<tr>
<td>用户名:</td><td><input type="text" name="" value=""></td>
</tr>
<tr>
<td>密码:</td><td><input type="password" name="" value=""></td>
</tr>
<tr>
<td><input type="submit" value="登录"></td>
</tr>
</table>
<hr>
<table>
<tr>
<td>用户名:</td><td>{{inp('text','uname')}}</td>
</tr>
<tr>
<td>密码:</td><td>{{inp('password','pwd')}}</td>
</tr>
<tr>
<td>{{inp('submit',value='登录')}}</td>
</tr>
</table>
</body>
</html>
运行结果:
2、宏的导入方式
2.1 from '宏文件的路径' import 宏的名字 [as xxx]。
{% from "users/users.html" import input as inp %}
2.2 import "宏文件的路径" as xxx [with context]
{% import "users/users.html" as usr with context %}
注意:
1. 宏文件路径,不要以相对路径去寻找,都要以 templates 作为绝对路径去找
2. 如果想要在导入宏的时候,就把当前模版的一些参数传给宏所在的模版,那么就应该在导入的时候使用 with context{% import "users/users.html" as usr with context %}
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>宏的引入</title>
</head>
<!--
from file import func_name
import file
-->
{% import 'macros/common.html' as mc with context %}
<!-- {% from 'macros/common.html' import inp with context %} -->
{% from 'macros/common.html' import inp%}
<body>
<h1>宏的引入</h1>
<table>
<tr>
<td>用户名:</td><td><input type="text" name="" value="{{nick}}"></td>
</tr>
<tr>
<td>密码:</td><td><input type="password" name="" value=""></td>
</tr>
<tr>
<td><input type="submit" value="登录"></td>
</tr>
</table>
<hr>
<table>
<tr>
<td>用户名:</td><td>{{ mc.inp(name='uname')}}</td>
</tr>
<tr>
<td>密码:</td><td>{{mc.inp('password','pwd')}}</td>
</tr>
<tr>
<td>{{ mc.inp('submit',value='登录')}}</td>
</tr>
</table>
<hr>
<table>
<tr>
<td>用户名:</td><td>{{ inp(name='uname')}}</td>
</tr>
<tr>
<td>密码:</td><td>{{inp('password','pwd')}}</td>
</tr>
<tr>
<td>{{ inp('submit',value='登录')}}</td>
</tr>
</table>
</body>
</html>