I’m trying to add an image to my quiz.html page with Flask using:
JavaScript
x
2
1
<img src='{{url_for('static', filename='img/question-mark.png')}}' alt='' >
2
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:
JavaScript
1
8
1
|-app.py
2
|-templates/
3
|-main.html
4
|-quiz.html
5
|-static/
6
|-css/
7
|-img/
8
app.py
JavaScript
1
15
15
1
from flask import Flask, render_template
2
3
app = Flask(__name__)
4
5
@app.route('/')
6
def homepage():
7
return render_template("main.html")
8
9
@app.route('/quiz/')
10
def quiz():
11
return render_template("quiz.html")
12
13
if __name__=="__main__":
14
app.run(debug=True)
15
Advertisement
Answer
You don’t need a Jinja script to write a static image source. Just write:
JavaScript
1
2
1
<img src="/static/img/question-mark.png">
2
All the static resources are automatically served under /static
.