2015-10-26 21 views
2

我正在使用Flask来学习Python并创建一个我想要制作的玩具应用程序。我遇到了标准文件上传的特定功能问题。我想要做的是试图动态渲染基于特定模型的图像文件夹中的图像,但我似乎在尝试进行字符串插值时遇到了问题。如何使用Jinja和Flask动态呈现来自我的图像文件夹的图像?

这里是我的视图代码:

<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 %} 

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

+1

“{{employee.profile_image}}”不应该放在引号内吗? –

回答

10

img标签应该是这样的

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

假设employee.profile_image相对于static/images/

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

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

嘿grotewold,谢谢你的答案,但这似乎并没有解决我的问题。当我硬编码诸如“static/images/profile.jpg”这样的路径时,它工作得很好。但是,当我尝试您的答案并查看Chrome开发人员工具时,employee.profile_image部分缺失。 –

+0

如果我按照上面的回答放置代码,则剩下src =“static/images /” –

+1

什么是'employee.profile_image'?什么是一个例子?现在描述的问题意味着'profile_image'属性中没有数据。 – groteworld

相关问题