Uma
Uma

Reputation: 29

How to display images from folder in Python html and flask

I am very new to python and Flask. I have a folder with a list of jpeg images. I have to display them in my demo application with flask as below, My app.py :

@app.route("/")
def home():  
    return render_template('home.html')

My home.html:

<img id="person" src={{ url_for('static',filename='pferson_folder/000_1.jpg') }}>

In the above code, I don't want to hardcode the images in the HTML tag. it needs to take the image source from folder dynamically.

Would you please help me with this. Thank you.

Upvotes: 2

Views: 10633

Answers (1)

TsungJui Wang
TsungJui Wang

Reputation: 328

You can read all the file names out of the directory using os.listdir('Your path') and pass the array into the template:

Something like:

# Inside app.py
import os
@app.route('/')
def home():
 image_names = os.listdir('Your path to images folder')
 render_template('home.html', image_name=image_names)

And inside your template:

{% for name in image_names %}
 <img src="{{ url_for('static', filename='pferson_folder/' + name) }}" >
{% endfor %}

Then you don't have to hardcode the names.

Upvotes: 4

Related Questions