静态文件主要包括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')
执行,可以在页面看到:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有