how to access variables in thymeleaf templates using spring mvc

Viewed 8883

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>
1 Answers
Related