Skip to content
Advertisement

Flask url_for – incorrect static folder path

I’m trying to add an image to my quiz.html page with Flask using:

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

When I look at the page source, it’s interpreted as: http://127.0.0.1:5000/quiz/static/img/question-mark.png rather than:
http://127.0.0.1:5000/static/img/question-mark.png

Yet, my .css files and .js files load in quiz.html using the same syntax just fine. How can I get the correct static file path?

My current structure is:

 |-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)

Advertisement

Answer

You don’t need a Jinja script to write a static image source. Just write:

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

All the static resources are automatically served under /static.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement