How can I dynamically render images from my images folder using Jinja and Flask?

Your img tag should look like this

<img src="static/images/{{ employee.profile_image }}" alt={{ employee.name }} width="120" height="90" />

Assuming employee.profile_image is the path relative to static/images/

If there is no profile_image value but you want to show a default, you can also use Jinja2's default filter like so.

<img src="static/images/{{ employee.profile_image | default('profile.jpg') }}" alt={{ employee.name }} width="120" height="90" />

Assuming:

  • Your images folder is located inside the static folder
  • You only store full file_name and not the path inside employee.profile_image

You can use following alternative to load images to Jinja2 template:

<img src="{{ url_for('static', filename = 'images/'+employee.profile_image) }}" alt="">

(Notice that there is no {} arround employee.profile_image.)

The difference between this method and the other is that when you try to load your image from let's say employees/employee_details.html template, you get the correct path for your image: /static/images/employee_image_1.jpg.

But if you try to do the same with <img src="static/images/{{ employee.profile_image }}" alt="" />, your path can end up being: /employees/static/images/employee_image_1.jpg which is not what you want.

Tags:

Python

Flask