1

I have a directory full of images. In one of my templates, I want to display these images

GET template:

render_template("registration.html", images=images)

in template: (using image/{{image}} because url_for doesn't accept variables)

{% for image in images %}
    <input  class="avatar" type = "radio" name = "avatar" value = "{{image}}"/><img src = "image/{{image}}"/>
{% endfor %}

and in app.py

@app.route('/images/<image>')
def images(image):
    return send_file('public/assets/thumbs'+image, mimetype='image/jpg')

(public/assets/thumbs is the directory images reside in) however, this fails completely. Is there any tricks or hacks I can use to make this work?

Andrew Allbright
  • 3,721
  • 3
  • 20
  • 23

2 Answers2

2

I don't know if it could help you neither if the method i'll describe is good practice but to display images from directory (using send_from_directory in my view as described below by Andrew Allbright) in templates I was using :

{% for image in images %}
<img src="{{url_for('static', filename='image/')}}{{image}}"></img>
{% endfor %}

I remember I took inspiration from this SO post: Create dynamic URLs in Flask with url_for() (second answer) that indicates you can pass argument to url_for() in your templates.

Community
  • 1
  • 1
lkostka
  • 711
  • 1
  • 5
  • 10
  • Have you verified that this works? Right now, my directory method sucks when the directory is full of .jpg, .jpeg, .png image files :) Edit: I suppose I'll check myself. I have a module that needs images and I think I'll try this out. Fingers crossed it just works :D – Andrew Allbright May 13 '14 at 21:54
1

Solution: send_from_directory()

@app.route("/image/<image>", methods=["GET"])
def image(image):
    return send_from_directory(app.static_folder, 'assets/thumbs/' + image, mimetype='image/jpg')
Andrew Allbright
  • 3,721
  • 3
  • 20
  • 23