Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access variables in thymeleaf templates using spring mvc

How can I access the variables I add to model in Spring MVC inside the thymeleaf templates? I have the following controller code:

@Controller
public class ThymeLeafController {

    @GetMapping("/thyme")
    public void thymeleaf(ModelAndView modelAndView) {
        modelAndView.addObject("var1", "var1");
        modelAndView.addObject(Arrays.asList("var2", "var3", "var4"));
        modelAndView.getModel().put("var5", "var5");
        modelAndView.getModelMap().addAttribute("var6", "var6");
        modelAndView.getModelMap().addAttribute(Arrays.asList("var7", "var8", "var9"));

        modelAndView.setViewName("thymeleaf");
    }
}

How can I access the variables var1, var5, var6, etc. inside thymeleaf templates?

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Thymeleaf</title>
</head>
<body>
<div th:if="#{var1}"></div>

</body>
</html>
like image 381
Ali Avatar asked Oct 24 '25 08:10

Ali


1 Answers

Behavior:

Accessing the attributes depends upon where they were added. If the attributes were added to the ModelAndView object, they must be accessed throught "${modelAndView.model.xxxx}" where xxxx is the attribute name. If the attributes were added to Model object, they are accessible using just the attribute name itself "${attributeName}". See example below.

Controller:

@GetMapping("/thyme")
public void thymeleaf(ModelAndView modelAndView, Model model) {
    modelAndView.addObject("var1", "var1");
    modelAndView.addObject(Arrays.asList("var2", "var3", "var4"));
    modelAndView.getModel().put("var5", "var5");
    modelAndView.getModelMap().addAttribute("var6", "var6");
    modelAndView.getModelMap().addAttribute(Arrays.asList("var7", "var8", "var9"));

    model.addAttribute("attribute1", "attributeValue1");

}

Template:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Thymeleaf</title>
</head>
<body>
<div th:text="${attribute1}"></div>
<div th:text="${modelAndView.model}"></div>
<div th:text="${modelAndView.model.var1}"></div>
</body>
</html>

Output:

attributeValue1
{var1=var1, stringList=[var7, var8, var9], var5=var5, var6=var6}
var1
like image 100
Ali Avatar answered Oct 28 '25 06:10

Ali