在项目开发过程中会用到大量的静态文件来使得网页更加生动美观。如CSS样式文件、JavaScript脚本文件、图片文件、字体文件等静态资源。
使用Jinja加载静态文件只需要通过url_for全局函数就可以实现。
<link href="{{ url_for('static',filename='base.css') }}">
url_for函数默认会在项目根目录下的static文件夹中寻找base.css文件,如果找到了,会生成一个相对于项目根目录下的/static/base.css路径。这个静态文件的路径也不是固定不能变的,也可以自己来指定的。
# 当访问静态文件的时候,将自动到/static/路径下去寻找文件
app = Flask(__name__, static_folder="C:\static")
简单实现示例代码:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
{# <link rel="stylesheet" href="../static/css/index.css">#}
<link rel="stylesheet" href="{{ url_for('static', filename='css/index.css') }}">
</head>
<body>
<div class="detail">
您好,我是红色字体
</div>
<div>
您好,我是黑色字体
</div>
</body>
</html>
index.css
.detail {
color: red;
}
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()
运行效果: