以下分别介绍flask如何加载static文件中的img、css、js静态资源
一、项目配置
在项目中创建static文件,在此文件下再新建images、css、js文件夹,并将所要展示的资源存入对应文件下。
二、代码详情
1、app.py
@app.route('/static')
def static_demo():
return render_template("static.html")
#static.html为该路径展示页面(新建)
2、static.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>加载静态资源文件</title>
<!--通过link链接css | 通过script链接js-->
<!--src="{{}}" href="{{}}"-->
<!--通过url_for函数调用静态资源,第一个参数static为指定的静态资源文件夹,filename='static文件夹下的路径'-->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="{{ url_for('static', filename='js/my.js') }}"></script>
</head>
<body>
<img src="{{ url_for('static', filename='images/关注.jpg') }}" alt="">
</body>
</html>
3、js/my.js
// 一个窗口声明
alert("我是my.js中执行的!");
4、css/style.css和images/关注.jpg
body{
background-color: red;
}