D Emma
D Emma

Reputation: 317

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>.

Controller:

@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 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?

Upvotes: 5

Views: 2729

Answers (1)

AmirBll
AmirBll

Reputation: 1119

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

Upvotes: 4

Related Questions