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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33355159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:13:22  来源:igfitidea点击:

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

pythonflask

提问by Dan Rubio

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.

它应该非常简单。我被 ruby​​ 和 rails 宠坏了.... 帮助将不胜感激。谢谢。

采纳答案by groteworld

Your imgtag should look like this

你的img标签应该是这样的

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

Assuming employee.profile_imageis the path relative to static/images/

假设employee.profile_image是相对于的路径static/images/

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

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

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