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

I have some static image files under a directory of classpath, and I hope to pass the relative path of one of the image files by variable. On Thymeleaf, the target is that this variable will be used as the path for the src attribute of <img>.


public class SomeController {

    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 template:

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

The context within the angle brackets (inclusive) of th:src in the Thymeleaf template is exactly where I want to put the string of imageFilepath variable. Is such a target feasible?


you can use this without pass variable:

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

if you want to pass variable you can use this:

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