1、依赖
<!-- thymeleaf 模板启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2、模板存放路径
public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;//默认编码 public static final String DEFAULT_PREFIX = "classpath:/templates/";//模板位置 public static final String DEFAULT_SUFFIX = ".html";//模板文件后缀 }
3、thymeleaf基本语法
3、存值(通过ModelAndView)
@RequestMapping("get") public ModelAndView test(ModelAndView modelAndView) { student.setName("张三"); student.setAge(12); student.setBirthday(new Date()); modelAndView.addObject("stu", student); modelAndView.addObject("name", "123"); ArrayList<Student> list = new ArrayList<>(); list.add(student); list.add(student); modelAndView.addObject("list", list); modelAndView.setViewName("test"); return modelAndView; }
2、取单值【通过 th:text ="${xxx}" / th:utext="${xxx}"替换标签中的值 】
<td th:text="${stu.name}">121212</td>
<!-- 赋值 不转义特殊字符--> <p th:utext="'叶落<h1>无</h1>声'"></p>
<!-- 赋值 转义特殊字符--> <p th:text="'叶落<h1>无</h1>声'"></p>
3、取数组/集合 【th:each】
<tr th:each="list2:${list}"> <td th:text="123"> <td th:text="${list2.name}"> <td th:text="${list2.age}"> <td th:text="${list2.birthday}"> </td> </tr>
4、运算
4.1、四则运算 三目运算
<tr th:each="list2:${list}"> <td th:text="123"> <td th:text="${list2.name}"> <td th:text="${list2.age} * 3 >18 ? '成年':'未成年'"> <td th:text="${list2.birthday}"> </td> </tr>
5、判断
<!--如果标签中返回true显示该标签否则不显示--> <td th:if="${list2.age<18}">小于18</td> <!--如果标签中返回false显示该标签否则不显示--> td th:unless="${list2.age>18}">大于18</td> <!-- switch case判断 --> <tr th:switch="${stu.sex}"> <td th:case="1">男</td> <td th:case="0">女</td> <td th:case="*">不男不女</td> </tr>
5、直接取值 [ [ ${xxx} ] ]
<td >生日:[[${list2.birthday}]]</td>
6、在js中取值
<script th:inline="javascript"> var jsonStr=[[${json}]]; </script>
7、html语法爆红
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">