一、Thymeleaf 介绍
Thymeleaf 是用于 Web 和独立环境的现代服务器端Java模板引擎。其主要目标是将优雅的自然模板带到您的开发工作流程中— HTML 能够在浏览器中正确显示,并且可以作为静态原型,从而在开发团队中实现更强大的协作。
Thymeleaf 有六种模板模式,包括有 HTML,XML,JavaScript,CSS ,TEXT,RAW。
二、基本语法
1. 变量表达式${...}
变量表达式是OGNL表达式。使用方式:th:xxx="${xxx.xxx}"
,例如:
<form action="/test">
<input name="id" th:value="${user.id}"/>
<input name="name" th:value="${user.name}"/>
</form>
<div th:text="helloThymeleaf"></div>
<h3 th:text="${title}"></h3>
<div th:text="${user.name}"></div>
2. 选择表达式*{...}
选择表达式 *{...}
需要与 th:object
一同使用,使用方式是首先通过 th:object="${xx.xxx}
获取对象,然后通过 th:xxxx="*{vvvv}"
获取对象 xx.xxx
的属性 vvvv
的值,例如:
<form action="/indexThymeleaf" method="post" th:object="${user}">
<input name="id" th:value="*{id}"/>
<input name="name" th:value="*{name}"/>
<input type="submit" value="submit" />
</form>
后端代码为:
@RequestMapping("/indexThymeleaf")
public String indexThymeleaf(Model model, User user) {
model.addAttribute("title", "springboot整合Thymeleaf");
model.addAttribute("user", user);
return "indexThymeleaf";
}
3. 消息 (i18n) 表达式#{...}
消息表达式 #{...}
允许从外部源(如:.properties)文件中检索特定于语言环境的消息,通过键来引用这引用消息。例如:
首先在 src/main/resources/
下创建文件 messages.properties
,SpringBoot 会自动解析该目录下的该文件,在其中加入 msg = hello
,然后在html 文件中加入下面代码就可以获取其值
<div th:text="#{msg}"></div>
注意:文件名必须为 messages.properties
,否则 Thymeleaf 不能解析渲染 cus.val
的值,页面显示为 ??msg_zh_CN??
。
4. 链接 (URL) 表达式@{...}
使用链接表达式 @{...}
可以是相对路径也可是绝对路径,能够使用 @{…} 的标签主要有 th:action
,th:href
,th:src
,依次相当于 action
,href
,src
。例如:
<form th:action="@{/indexThymeleaf}" method="post" th:object="${user}">
<input name="id" th:value="*{id}"/>
<input name="name" th:value="*{name}"/>
<input type="submit" value="submit" />
</form>
<a th:href="@{/indexThymeleaf}">相对路径</a>
<a th:href="@{https://www.baidu.com/}">绝对路径</a>
<a th:href="@{/indexThymeleaf(id=id,name=name)}">相对路径-通过使用()传参</a>
<a th:href="@{/indexThymeleaf/{id}(id=2)}">相对路径-通过 restful风格进行参数传递</a>
5. 片段表达式~{...}
片段表达式 ~{...}
是一种简单的方法用来表示标记的片段并将其移动到模板中,常与 th:insert
或 th:replace
来插入片段,其中有三种语法:
~{ viewname }
:表示引入完整页面
~{ viewname :: selector}
:表示在指定页面寻找片段 其中selector可为片段名、jquery选择器等
~{ :: selector}
:表示在当前页寻找
例如:
声明模板片段src/main/resources/templates/test.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body th:fragment="foot">
hello Thymeleaf
</body>
</html>
引入模板片段:
<div th:include="test :: foot"></div>
三、Thymeleaf 内置对象
注意:
- 调用内置对象一定要用
#
- 大部分的内置对象都以 s 结尾 strings、numbers、dates
1. 七大基础对象
${#ctx}
:上下文对象,可用于获取其它内置对象${#vars}
:上下文变量${#locale}
:上下文区域设置${#request}
:HttpServletRequest对象${#response}
:HttpServletResponse对象${#session}
:HttpSession对象${#servletContext}
:ServletContext对象
例如:
获取 request 中的值:
request.setAttribute("req", "HttpServletRequest");
Request:<span th:text="${#httpServletRequest.getAttribute('req')}"></span>
获取 session 中的值:
request.getSession().setAttribute("sess", "HttpSession");
Session:<span th:text="${session.sess}"></span>
获取 aervletContext:
request.getSession().getServletContext().setAttribute("app", "Application");
Application:<span th:text="${application.app}"></span>
2. 常用工具对象
#strings
:字符串工具类,常用方法有:isEmpty(key)
,contains(msg,'T')
,length(msg)
,substring(msg,13,15)
#dates
:时间操作和时间格式化等,常用方法:format(key,'yyy/MM/dd')
,year(key)
#numbers
:格式化数字对象的方法#ids
:处理可能重复的id属性的方法#arrays
:数组工具类#lists
:List 工具类#sets
:Set 工具类#maps
:常用Map方法#objects
:一般对象类,通常用来判断非空#messages
:在变量表达式中获取外部消息的方法,与使用#{…}语法获取的方法相同
四、条件判断
用于条件判断主要有 th:if
和 th:unless
,其中 th:unless
表示取反。下面演示它们的用法:
<span th:if="${user.name} == '男'">性别:男</span>
<span th:if="${user.name} == '女'">性别:女</span>
<span th:unless="${user.name} == '女'">性别:男</span>
还有 th:switch
的用法如下:
<div th:switch="${user.id}">
<span th:case="1">ID 为 1</span>
<span th:case="2">ID 为 2</span>
<span th:case="3">ID 为 3</span>
</div>
五、迭代循环
下述实例统一使用一个Controller,主要代码:
@RequestMapping("/indexThymeleaf")
public String indexThymeleaf(Model model) {
List<User> list = new ArrayList<>();
list.add(new User("1", "zhangsan"));
list.add(new User("2", "lisi"));
list.add(new User("3", "wangwu"));
list.add(new User("4", "赵六"));
model.addAttribute("users", list);
Map<String, User> map = new HashMap<>();
map.put("11", new User("1", "zhangsan"));
map.put("12", new User("2", "lisi"));
map.put("13", new User("3", "wangwu"));
map.put("14", new User("4", "赵六"));
model.addAttribute("usersMap", map);
return "indexThymeleaf";
}
- 不使用状态变量迭代循环
不使用状态变量迭代循环users
中的对象,实例如下。
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr th:each="u : ${users}">
<td th:text="${u.id}"></td>
<td th:text="${u.name}"></td>
</tr>
</table>
- 使用状态变量迭代循环
使用状态变量迭代循环users
中的对象,实例如下。
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>index</th>
<th>count</th>
<th>size</th>
<th>even</th>
<th>odd</th>
<th>first</th>
<th>last</th>
</tr>
<tr th:each="u,var : ${users}">
<td th:text="${u.id}"></td>
<td th:text="${u.name}"></td>
<td th:text="${var.index}"></td>
<td th:text="${var.count}"></td>
<td th:text="${var.size}"></td>
<td th:text="${var.even}"></td>
<td th:text="${var.odd}"></td>
<td th:text="${var.first}"></td>
<td th:text="${var.last}"></td>
</tr>
</table>
状态变量属性:
index
:当前迭代器的索引 从 0 开始count
:当前迭代对象的计数 从 1 开始size
:被迭代对象的长度even/odd
:布尔值,当前循环是否是偶数/奇数 从 0 开始first
:布尔值,当前循环的是否是第一条,如果是返回 true 否则返回 falselast
:布尔值,当前循环的是否是最后一条,如果是则返回 true 否则返回 false
3. 迭代循环Map
迭代循环Map类型的对象。
<table border="1">
<tr>
<th>entrys</th>
</tr>
<tr th:each="entrys : ${usersMap}">
<td th:text="${entrys}"></td>
</tr>
</table>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>ID</th>
<th>Name</th>
<th>ID</th>
<th>Name</th>
</tr>
<tr th:each="entrys : ${usersMap}">
<!-- 方式一 -->
<td th:each="entry:${entrys}" th:text="${entry.value.id}" />
<td th:each="entry:${entrys}" th:text="${entry.value.name}" />
<!-- <td th:each="entry:${entrys}" th:text="${entry.key}" /> -->
<!-- 方式二 -->
<td th:each="entry:${entrys}">
<span th:text="${entry.value.id}"></span>
</td>
<td th:each="entry:${entrys}">
<span th:text="${entry.value.name}"></span>
</td>
<!-- <td th:each="entry:${entrys}">
<span th:text="${entry.key}"></span>
</td> -->
<!-- 方式三 -->
<td th:text="${entrys.value.id}" />
<td th:text="${entrys.value.name}" />
<!-- <td th:text="${entrys.key}" /> -->
</tr>
</table>
六、日期格式化和字符串拼接转义
通过使用时间工具类#dates
来对日期进行格式化
model.addAttribute("nowDate", new Date());
<div th:text="${#dates.format(nowDate,'yyy/MM/dd')}"></div>
通过运算符 +
字符串拼接
<div th:text="'当前时间:' + ${#dates.format(nowDate,'yyy/MM/dd')}"></div>
通过 th:utext
实现字符串转义
<div th:utext="${html}"></div>