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

In Spring Boot, how to pass a controller model variable to Thymeleaf th:src?

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

的 src 属性的路径

控制器:

@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";
    }
}

Thymeleaf 模板:

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

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

你可以在没有传递变量的情况下使用它:

<img th:src="@{/img/myPic.jpg}">

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

 <img th:src="${myPath}">