Search code examples
javaspringspring-mvctemplate-enginethymeleaf

Thymeleaf not displaying values from spring controller


I am practising thymeleaf template engine for the first time. I have followed the tutorial and so on but I have no idea where I am going wrong.

My controller:

public String mainPage(Model model){
    model.addAttribute("data", "Hello Thymeleaf");  
    return "main";
}

and my html is as follows:

<!DOCTYPE html >
<html xmlns:th="http://www.thymeleaf.org">

<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<body>
   <h1>th:text="${data}"</h1>
</body>
</html>

When I hit localhost it displays th:text="${data}" instead of Hello Thymeleaf

<h1>"${data}"</h1>

doesn't work either. View resolver config must be correct as it resolves main to main.html. I am using spring4 SpringTemplateEngine and spring4 thymeleaf view resolver.

thanks in advance


Solution

  • You have to use th:text

     <h1 th:text="${data}"></h1>
    

    or if you don't want to use the th:text attribute, then you have to use th:inline="text" and make the thymeleaf render the context inside the tag. But make sure you put the variable inside [[ and ]]

     <h1 th:inline="text">[[${data}]]</h1>