【问题标题】:Trouble with hosting template files using Flask [duplicate]使用 Flask 托管模板文件时遇到问题 [重复]
【发布时间】:2019-04-25 16:01:21
【问题描述】:

我想使用 Flask 框架在 app.py 的 /Project/templates 中托管 3 个文件。这是它的样子。

Project
├── templates
│   ├── index.html
│   ├── index.js
|   └── style.css
├── app.py

如何使用 Flask 框架在 app.py 中托管这些文件?这是我的尝试,但它给了我一个空白页。

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index_html():
    return render_template('index.html')

@app.route('/index.js')
def index_js():
    return render_template('index.js')

@app.route('/style.css')
def style_css():
    return render_template('style.css')

if __name__ == '__main__':
    app.run(debug=True)

【问题讨论】:

标签: javascript python html css flask


【解决方案1】:

我相信index.jsstyle.css 是静态文件。因此,要访问它们,请在与模板相同的目录中创建一个文件夹 static。所以结构看起来是这样的

Project
├── templates
│   └── index.html
├── static
│   ├── index.js
│   └── style.css
└── app.py

然后在模板中,例如index.html,将它们包含在

<script type="text/javascript" src="{{ url_for('static', filename='index.js') }}"></script>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多