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
How can I dynamically render images from my images folder using Jinja and Flask?
提问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 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
值但你想显示一个默认值,你也可以default
像这样使用 Jinja2 的过滤器。
<img src="static/images/{{ employee.profile_image | default('profile.jpg') }}" alt={{ employee.name }} width="120" height="90" />