1.加入启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.在resources/templates下创建html文件
3.html页面加入命名空间 :将会有语法提示
<html lang="en" xmlns:th="http://www.thymeleaf.org">
4.thymeleaf基础语法
package com.acofkings.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Arrays;
@Controller
public class IndexController {
@RequestMapping("/test")
public String index(Model model){
model.addAttribute("msg","<h1>hello</h1>");
model.addAttribute("users", Arrays.asList("acofkings","tjndsg"));
return "test";
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--所有的html语句都可以被thymeleaf接管 th:元素名-->
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div><!--不转义-->
<!--th:each 俩种写法-->
<h3 th:each="user:${users}" th:text="${user}"></h3><!--推荐第一种写法-->
<h3 th:each="user:${users}"> [[${user}]] </h3>
</body>
</html>
spring:
thymeleaf:
cache: false
#关闭模板引擎thymeleaf的缓存
当获取内容为url时 使用@{}
<!-- Bootstrap core CSS -->
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="@{/css/signin.css}" rel="stylesheet">
使用国际化时 使用#{}
<form class="form-signin" action="dashboard.html">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 th:text="#{login.tip}" class="h3 mb-3 font-weight-normal">Please sign in</h1>
<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<input type="password" class="form-control" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<input type="checkbox" value="remember-me"> [[#{login.remeber}]]
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn} ]]</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/index(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index(l='en_US')}">English</a>
</form>
fragment使用~{}
<nav th:fragment="top"></nav>
<!--定义fragment片段-->
<div th:insert="~{dashboard::top}"></div>
<!--
插入片段 div中插入一个div
~{html名::片段名}
实现代码的复用
-->
<div th:replace="~{dashboard::top}"></div>
<!--
替换 直接替换div
-->
<!-- 可传递参数 -->
<div th:replace="~{commons/commons::sidebar(active='main.html')}"></div>
<!-- 通过传递的参数进行片段 ()-->
<a th:class="${active=='main.html'?'nav-link active':'nav-link'}" th:href="@{/main.html}">
<p th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p><!--如果msg的值为空就不显示消息-->
<td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}"></td><!-- 日期格式化-->