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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.