Thymeleaf not displaying values from spring controller

心不动则不痛 提交于 2019-12-08 10:45:13

问题


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


回答1:


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>



回答2:


Thymeleaf isn't Velocity or Freemarker and doesn't replace expressions blindly. You need the expression in an appropriate tag attribute, such as

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



回答3:


remove quotes to "${data}" and just use ${data}. I also agree with @Faraj Farook



来源:https://stackoverflow.com/questions/29569682/thymeleaf-not-displaying-values-from-spring-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!