Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

flask

I am using Flask to learn Python and to create a toy application that I've wanted to make for awhile. I'm having problems with a particular feature which is the standard file uploading. What I want to do is to try to dynamically render an image from my images folder based on a particular model but I seem to be having a problem trying to string interpolate.

Here is my view code:

<h1>List of Employees</h1>

{% if employees %}
    {% for employee in employees: %}
      <p>{{ employee.name }}</p>
      <p>{{ employee.title }}</p>
      <p>{{ employee.email }}</p>
      <p>{{ employee.department }}</p>

      # How do I use Jinja and python to interpolate this so I can 
      # grab the correct image
      <img src="static/images/" + {{employee.profile_image }} alt={{ employee.name }} width="120" height="90">{{ employee.profile_image }}</img>
    {% endfor %}
  {% endif %}

It should be very straightforward. I have been spoiled by ruby and rails.... Help would be appreciated. Thanks.

like image 398
Dan Rubio Avatar asked Oct 26 '15 20:10

Dan Rubio


1 Answers

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" />
like image 187
groteworld Avatar answered Sep 28 '22 12:09

groteworld