我正在尝试在 html <img src=...> 标记中创建一个 url_for,其中图像的文件名存储在一个变量中。我该怎么做?

I'm trying to create an url_for in an html <img src=...> tag where the filename for the image is stored in a variable. How would I do this?

我正在尝试为用户创建一个页面来显示他们的个人资料图片,我已经从数据库中检索了图片文件名并将该文件名存储为名为 "profilePic" 的变量。

我已将 profilePic 作为变量传递给 html 页面,但我如何使用 Jinja2 的 {{ url_for }} 创建 <img> 标签。如果我只输入图片名称,我知道该怎么做,但在这种情况下,图片的名称会因用户而异。

我试过了...

<img src="{{ url_for('static', filename='img/user/{{ profilePic }}' }}>

这不起作用,因为您似乎无法在 Jinja2 中嵌套 {{ }} 项。

我该怎么做?

您可以使用 +

在您的模板中执行正常的字符串连接
<img src="{{ url_for('static', filename='/img/user/' + profilePic) }}" />

.join

<img src="{{ url_for('static', filename='/'.join(['img', 'user', profilePic])) }}" />