由于spring boot取消了对velocity模板语言的支持,因此只能换成其他语言了,现在我选择Thymeleaf,毕竟官方推荐。
一上手Thymeleaf非常不习惯,它跟常用的Java语法格式相差甚远。甚至跟HTML语言非常相似。
下面是Java项目常用的Thymeleaf语法,我一一做了实验:
Thymeleaf语言风格
在进行一些简单的操作,例如,分支,循环等。Thymeleaf会作为一种标签的属性,在属性中取值并显示。这就是它的风格。
例如:
Controller包中的文件:
1 @Controller 2 public class deal { 3 @RequestMapping(path = {"/hello"}) 4 public String Hello_World(Model model) { 5 model.addAttribute("aaa", "naive"); 6 model.addAttribute("l", "<br/>"); 7 return "Hello"; 8 }
Templates包中的模板:
1 <html> 2 <head> 3 <title>Welcome!</title> 4 </head> 5 <body> 6 <!--/* 7 fdsfd 8 <h1>Welcome</h1> 9 */--> 10 <p th:text=${aaa}></p> 11 <p>th:utext=${aaa}</p> 12 <p th:utext=${aaa}>th:utext=${aaa}</p> 13 // 14 <p th:text=${aaa}></p> 15 <p th:utext=${aaa}></p> 16 <p th:utext=${l}></p> 17 </body> 18 </html>
显示结果:
总结:只有把一些标签属性,例如th:text,th:utext等放到<p>标签内,网页才能正常显示Controller文件定义好的变量值。
注释
建议用<!--/* *-->这个,可以注释多行。
1 <!--/* 2 fdsfd 3 <h1>Welcome</h1> 4 */-->
同时取消注释也简单。
1 <!--/*/ 2 fdsfd 3 <h1>Welcome</h1> 4 /*/-->
显示文本
th:text或者th:utext
1 <p th:text=${aaa}></p> 2 <p>th:utext=${aaa}</p> 3 <p th:utext=${aaa}>th:utext=${aaa}</p>
显示结果:
总结:th:text都可以显示文本,把属性放到<p></p>标签里面,可以显示C层变量(第一行)。放到<p></p>中间夹住,不能取值(第二行)。同时标签中的值会取消夹住地方的值。(第三行)
th:text不能解析标签,但是th:utext能。如下:
1 model.addAttribute("l", "<br/>");
使用l变量:
1 <p th:text=&{l}></p>
出错:There was an unexpected error (type=Internal Server Error, status=500).Could not parse as expression: "&{l}" (template: "Hello" - line 13, col 6)。它表示th:text无法解析l变量中的标签。
换一种写法:
1 <!--/*--> 2 <p th:text=&{l}></p> 3 <!--*/--> 4 <p th:utext=${l}></p>
5 <p>th:utext=${aaa}</p>
显示结果: