Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 583
D Emma Avatar asked Apr 11 '21 02:04

D Emma


1 Answers

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}">
like image 83
AmirBll Avatar answered Oct 20 '22 22:10

AmirBll