2

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.

Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24
Uma
  • 29
  • 1
  • 5

1 Answers1

4

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.

TsungJui Wang
  • 328
  • 1
  • 4