静态文件主要包括css
,JavaScript
等脚本文件、图片等,在加载文件的时候主要是用url_for
方法。
url_for('文件夹', filename='调用文件路径及扩展名')
我们先在static
文件夹新建js
、css
文件夹,并新建对应扩展名的文件:
然后在index
文件夹下新建mystatic.html
文件,对应代码:
window.onload = function(){
alert('hello world')
}
此代码意思是弹出alert
提示框
body{
background: aquamarine;
}
这里只是设置了一下背景颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>静态文件</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/mystatic.css') }}">
<script src="{{ url_for('static', filename='js/mystatic.js') }}"></script>
</head>
<body>
</body>
</html>
注意:在mystatic.html
中,分别通过link
和script
标签,利用url_for
调用了对应的静态文件。
在app.py
中增加函数:
@app.route('/mystatic/')def mystatic():
return flask.render_template('index/mystatic.html')
执行,可以在页面看到: