首页 > 解决方案 > 将 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 文件等。因为如果没有加载,我的网页看起来很枯燥。它只是白屏上的一些文字。我认为问题在于加载静态文件,因为我收到一条错误消息,指出本地主机上没有文件夹资产。

提前致谢。

标签: pythonflask

解决方案


您需要像这样引用模板中的静态文件:

<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

并确保将样式表放在static项目目录中。您还可以配置哪个目录包含静态资产,例如:

app = Flask(__name__, static_folder="static_dir")

推荐阅读