在Spring Boot中,如何将控制器模型变量传递给Thymeleaf th:src?

D E*_*mma 5 java spring spring-mvc thymeleaf spring-boot

我在classpath的目录下有一些静态图像文件,我希望通过变量传递其中一个图像文件的相对路径。在 Thymeleaf 上,目标是该变量将用作 src 属性的路径<img>

控制器:

@Controller
public class SomeController {

    @RequestMapping("/some")
    public String someRequest(Model model) {
        String imageFilepath = someObject.getImageFilepath();
        // e.g., if imageFilepath = "/img/myPic.jpg", there can be a file "/img/myPic.jpg" under classpath:static
        model.addAttribute("myPath", imageFilepath);
        return "myThymeleafTemplate";
    }
}
Run Code Online (Sandbox Code Playgroud)

百里香叶模板:

<img th:src="@{<I want to use my variable 'myPath' here instead of a hard-coded string '/img/myPic.jpg'>}">
Run Code Online (Sandbox Code Playgroud)

Thymeleaf 模板中 th:src 的尖括号(含)内的上下文正是我想要放置imageFilepath变量字符串的位置。这样的目标可行吗?

Ami*_*Bll 4

您可以在不传递变量的情况下使用它:

<img th:src="@{/img/myPic.jpg}">
Run Code Online (Sandbox Code Playgroud)

如果你想传递变量,你可以使用这个:

 <img th:src="${myPath}">
Run Code Online (Sandbox Code Playgroud)