如何使用Jinja和Flask从我的图像文件夹动态渲染图像?

时间:2021-10-27 00:31:05

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.

我正在使用Flask来学习Python并创建一个我想要制作一段时间的玩具应用程序。我遇到了标准文件上传的特定功能问题。我想要做的是尝试根据特定模型从我的图像文件夹动态渲染图像,但我似乎在尝试字符串插值时遇到问题。

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.

它应该非常简单。我被红宝石和铁轨宠坏了......帮助将不胜感激。谢谢。

1 个解决方案

#1


13  

Your img tag should look like this

你的img标签看起来应该是这样的

<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/

假设employee.profile_image是相对于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.

如果没有profile_image值但你想显示默认值,你也可以像这样使用Jinja2的默认过滤器。

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

#1


13  

Your img tag should look like this

你的img标签看起来应该是这样的

<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/

假设employee.profile_image是相对于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.

如果没有profile_image值但你想显示默认值,你也可以像这样使用Jinja2的默认过滤器。

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