0

I have this python flask bootstrap function:

# Index page (main page)
@app.route('/')
def index():
    return render_template('test.html')

And my run code:

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

Of course the default folder will be under the (relative) templates directory so I have there:

templates/test.html templates/images/logo.svg

The source of test.html is:

<!DOCTYPE html>
<html lang="en">
<body>
Hello
<img src="/images/logo.svg">
<img src="images/logo.svg">
</body>
</html>

But when I load the page with the flask supplied link to the app, both images are broken.

I'm guessing my path to my logo.svg is wrong. How do I figure out where it is relative to the app's root?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Hein du Plessis
  • 3,305
  • 6
  • 34
  • 51
  • 1
    By using `url_for`. Your image should be in `static`, not `templates` because it's not a template – roganjosh Apr 30 '23 at 16:11
  • 1
    Does this answer your question? [Link to Flask static files with url\_for](https://stackoverflow.com/questions/16351826/link-to-flask-static-files-with-url-for) – roganjosh Apr 30 '23 at 16:11
  • Thanks, I've come across url_for but using it means I won't be able to see the site by just opening the HTML file. This makes designing or customising third party templates very hard. Happy to mark your answer as correct if you post it as such. – Hein du Plessis Apr 30 '23 at 16:27
  • I don't need to post as an answer, you can just accept the dupe that I listed. There should be no need to open the `html` files directly because you have `debug=True` so just refresh the page; the templates won't be cached in that case, so leave the server running – roganjosh Apr 30 '23 at 16:28
  • @roganjosh The only issue I have is the template I'm using has 100s of static links to resources. It makes for some really tricky find and replace actions (from hardcoded paths to the url_for option). I have a feeling I'm going about this all wrong. I should not be this hard to make use of a 3rd party designed template. – Hein du Plessis Apr 30 '23 at 16:48
  • 2
    They shouldn't have been hard-coded in the first place. If you're going to take a pre-made template then it's basically incumbent on you to make these replacements – roganjosh Apr 30 '23 at 17:17

1 Answers1

1

To fix the problem:

  1. Add your images to the static folder in your project, so the path to the logo file will be like ./static/images/logo.svg
  2. Use <img src="{{ url_for('static', filename='images/logo.svg') }}"> in you template.

To know more about static files in Flask read the documentation.

Taras Drapalyuk
  • 473
  • 3
  • 6