thymeleaf 是 springboot 中流行使用的模板引擎,语法简单,功能强大。
thymeleaf 官方帮助文档(英文版)thymeleaf.pdf 提取密码: zev2
引入 thymeleaf
pom 文件引入 thymeleaf 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如果想要更改默认的版本,可加入如下代码更改 thymeleaf 版本
注意:thymeleaf-layout-dialect 的 2.0 及以上版本才开始支持 thymeleaf 的 3.0 以上版本
<properties>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
</properties>
thymeleaf 的语法
引入名称空间
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
如果不引入名称空间,可以使用 data-th-属性 使用 thymeleaf 功能,如下
<p data-th-text="#{home.welcome}">Welcome to our grocery store!</p>
标准表达式语法
Simple expressions: 简单表达式
Variable Expressions: ${...} 变量表达式,获取变量的值,OGNL实现
1) 获取对象的属性、调用方法
例如:
${person.father.name}
${personsByName['Stephen Zucchini'].age}
${person.createCompleteName()}
2) 使用内置的基本对象
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.
例如:
Established locale country: <span th:text="${#locale.country}">US</span>.
3) 使用内置的工具对象
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
例如:
${#strings.toString(obj)} // also array*, list* and set*
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
Selection Variable Expressions: *{...} 选择表达式,功能同 ${...}
额外功能:与 th:object 配合使用,* 代表 th:object
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
Message Expressions: #{...} 信息表达式,获取国际化内容
Link URL Expressions: @{...} 定义 url 表达式
/ 代表当前项目下,参数都以键值对写在()中
例如:
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
@{/order/process(execId=${execId},execType='FAST')}
Fragment Expressions: ~{...} 片段表达式
例如:
<div th:insert="~{commons :: main}">...</div>
<div th:with="frag=~{footer :: #main/text()}">
<p th:insert="${frag}">
</div>
Literals 直接常量
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,…
Text operations: 文本操作
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations: 算术运算
Binary operators: + , - , * , / , %
Minus sign (unary operator): -
Boolean operations: 逻辑运算
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality: 比较运算
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators: 条件判断
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens: 特殊符号
No-Operation: _ (不做操作)
属性优先级
Order | Feature | Attributes |
---|---|---|
1 | Fragment inclusion (片段包含,类似 jsp:include) | th:insert th:replace |
2 | Fragment iteration (遍历,类似 c:forEach) | th:each |
3 | Conditional evaluation (条件判断,类似 c:if ) | th:if th:unless th:switch th:case |
4 | Local variable definition (变量声明,类似 c:set ) | th:object th:with |
5 | General attribute modification (一般属性修改) | th:attr th:attrprepend th:attrappend |
6 | Specific attribute modification (特殊属性修改) | th:value th:href th:src … |
7 | Text (tag body modification) (标签体内容修改) | th:text (转义特殊字符) th:utext (不转义特殊字符) |
8 | Fragment specification (片段声明) | th:fragment |
9 | Fragment removal (片段移除) | th:remove |
使用案例
thymeleaf 的使用比较简单,只是把 html 的原生属性都替换即可,简单用法示例如下:
在资源文件夹下新建 templates 文件夹,在其中创建 success.html 文件,thymeleaf 会默认去这个文件中找 html 文件
success.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>thymeleaf 使用</title>
</head>
<body>
<h1>Welcome !</h1>
<div th:text="${uname}">这是显示姓名 text</div>
<div th:utext="${uname}">这是显示姓名 utext</div>
<div th:text=${#strings.isEmpty(uname)}>uname是否为空</div>
<div id="oldid" th:id="${newid}" class="oldclass" th:class="${newclass}">id class 被替换</div>
<hr/>
<!-- th:each 每次遍历都会生成当前标签 -->
<h3 th:each="obj:${person}" th:text="${obj}"></h3>
<h3>
<span th:each="obj:${person}"> [[${obj}]]</span>
</h3>
</body>
</html>
controller 类
package com.xiao.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
@ResponseBody
@RequestMapping(name="/hello")
public String sayHello() {
return "hello";
}
@RequestMapping("/success")
public String testThy(Map<String, Object>map) {
map.put("uname", "<h1>张三</h1>");
map.put("person", Arrays.asList("小赵","小钱","小孙"));
return "success";
}
}
运行启动类,输入 localhost:8080/success ,页面如下