有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在Spring Boot中,如何将控制器模型变量传递给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变量字符串的位置。这样的目标是否可行


共 (1) 个答案

  1. # 1 楼答案

    您可以在不使用pass变量的情况下使用此变量:

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

    如果要传递变量,可以使用以下命令:

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