python - 将 Web 模板与 Flask 集成
问题描述
我已经下载了一个网站模板,我想将它与烧瓶集成。基本上,此模板包含asset
包含 css 和 js 文件的文件夹。我知道通过使用render_template('index.html')
,我可以在本地主机上调用 index.html。但是当我这样做时,网页没有正确呈现。我认为烧瓶无法加载该文件夹(模板文件夹)中的 js、css 等文件。
我的模板文件夹有 index.html 以及 assets 文件夹和其他文件夹。我正在使用下面显示的代码来实际运行 index.html。
from flask import Flask, render_template
import os
app = Flask(__name__)
@app.route('/')
def homepage():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
所以,index.html 正在加载,但它没有加载 css 文件等。因为如果没有加载,我的网页看起来很枯燥。它只是白屏上的一些文字。我认为问题在于加载静态文件,因为我收到一条错误消息,指出本地主机上没有文件夹资产。
提前致谢。
解决方案
您需要像这样引用模板中的静态文件:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
并确保将样式表放在static
项目目录中。您还可以配置哪个目录包含静态资产,例如:
app = Flask(__name__, static_folder="static_dir")
推荐阅读
- python - Python如何按排行榜的数字顺序对元组(字符串,int)进行排序
- python - sudo pip3 install pygame 和 sudo apt install python3-pygame 有什么区别
- mysql - Combining multiple LIKE and NOT LIKE in the same mysql query
- google-bigquery - Understanding Google Bigquery materialized views pricing
- javascript - javascript类中的静态异步函数
- mysql - MySQL Select Query 排除日期
- javascript - Tronweb 和 Trongrid 错误:请求失败,状态码 502
- javascript - 如何在 p5.play 中向鼠标旋转精灵?
- delphi - 检查在线文件是否存在的可靠方法
- python - Jupyter notebook:当我打开一个存在或创建一个新的 .ipynb 文件时,显示一个错误:“500:无效的继续字节”