【问题标题】:Flask url_for - incorrect static folder pathFlask url_for - 不正确的静态文件夹路径
【发布时间】:2017-08-04 22:05:15
【问题描述】:

我正在尝试使用 Flask 将图像添加到我的 quiz.html 页面:

<img src='{{url_for('static', filename='img/question-mark.png')}}' alt='' >

当我查看页面源代码时,它被解释为: http://127.0.0.1:5000/quiz/static/img/question-mark.png 而不是:
http://127.0.0.1:5000/static/img/question-mark.png

然而,我的.css 文件和.js 文件使用相同的语法加载到quiz.html 中就好了。如何获取正确的静态文件路径?

我目前的结构是:

 |-app.py
 |-templates/
   |-main.html
   |-quiz.html
 |-static/
   |-css/
   |-img/

app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def homepage():
    return render_template("main.html")

@app.route('/quiz/')
def quiz():
    return render_template("quiz.html")

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

【问题讨论】:

  • 你从烧瓶中导入 url_for 了吗?请不要把""和''混在一起,你能把它们分开吗?
  • 看这个例子:跨度>

标签: python flask


【解决方案1】:

您不需要 Jinja 脚本来编写静态图像源。随便写:

<img src="/static/img/question-mark.png">

所有静态资源都自动在/static下服务。

【讨论】: