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')
Question
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?
Solution 2
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')
OTHER TIPS
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.