如何在 Spring 中使用 thymeleaf 将变量放入 img src 路径?

Kio*_*oni 1 spring spring-mvc thymeleaf spring-boot

好吧,我希望我的图像在 Front(html) 中显示表格数据。我使用 model.addAttributes 来传递玩家信息。我原来的 imgfile 在路径中:/img/

这是我的问题代码如下:

<tbody>
      <tr th:each="players : ${players}">
        <td><img src="/img/ + ${players.id} + '_' + ${players.name} + '.png'" width="120"/></td>
Run Code Online (Sandbox Code Playgroud)

我的图像命名总是用“id+name”.png 定义。我不知道如何将它组合到 img src 路径。我想要的解决方案是像下面这样工作:

        <td><img src="/img/1_pogba.png" width="120"/></td>
Run Code Online (Sandbox Code Playgroud)

Aji*_*man 5

您应该使用th:srcwithimg标签而不是普通src属性。只需从此更改您的 img 标签:

<img src="/img/ + ${players.id} + '_' + ${players.name} + '.png'" width="120"/>
Run Code Online (Sandbox Code Playgroud)

对此:

<img th:src="@{${'/img/' + players.id +'_'+ players.name + '.png'}}" width="120"/>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,您可以查看此链接:

https://www.thymeleaf.org/doc/articles/standardurlsyntax.html

  • 我推荐这样的表达式: `th:src="@{/img/{id}_{name}.png(id=${players.id},name=${players.name})}"` (3认同)