本文作者:Spring_ZYL
意见反馈:[email protected]
文章来源:https://blog.csdn.net/gozhuyinglong
版权声明:本文版权归作者所有,转载请注明出处
一、引入Thymeleaf依赖
在pom文件中添加如下内容
<!--引入thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
二、简单实例
Thymelea会自动渲染classpath:/templates/
下的文件,我们将html文件放入,即可使用
Controller代码如下:
package com.zyl.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.HashMap;
import java.util.Map;
@Controller
public class HelloController {
final String SUCCESS = "success";
@RequestMapping("/success")
public String success(Map<String, Object> map){
// classpath:/templates/success.html
map.put("hello","你好!");
return SUCCESS;
}
}
在resources/templates/
下创建success.html
为了方便使用Thymeleaf标签,我们引入如下命名空间
<html xmlns:th="http://www.thymeleaf.org">
html详细代码代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
Success!
<p th:text="${hello}"></p>
</body>
</html>
通过http://127.0.0.1:8080/success可访问
测试结果:
三、Thymeleaf标签属性
序号 特征 属性
1 片段包含 th:insert th:replace
2 片段迭代(遍历) th:each
3 条件判断 th:if th:unless th:switch th:case
4 声明变量 th:object th:with
5 一般属性修改 th:attr th:attrprepend th:attrappend
6 特定的属性修改 th:value th:href th:src ...
7 文本(标签主体修改) th:text th:utext
8 声明片段 th:fragment
9 移除片段 th:remove
四、Thymeleaf表达式语法
首先,我们来看一下Thymeleaf表达式快速总结:
- 简单表达式
- 变量表达式: ${…}(OGNL表达式)
- 选择变量表达式: *{…}
- 消息表达式: #{…}(获取国籍化内容)
- 链接URL表达式: @{…}(定义URL链接)
- 片段表达式: ~{…}(片段引用)
- 文字
- 文本文字:’one text’,’Another one!’,…
- 号码文字:0,34,3.0,12.3,…
- 布尔文字:true,false
- 空文字: null
- 文字标记:one,sometext,main,…
- 文字操作
- 字符串连接: +
- 文字替换: |The name is ${name}|
- 算术运算
- 二元运算符:+,-,*,/,%
- 减号(一元运算符): -
- 布尔运算
- 二元运营商:and,or
- 布尔否定(一元运算符): !,not
- 比较和平等
- 比较:>,<,>=,<=(gt,lt,ge,le)
- 平等运营商:==,!=(eq,ne)
- 有条件的操作符
- IF-THEN: (if) ? (then)
- IF-THEN-ELSE: (if) ? (then) : (else)
- 默认: (value) ?: (defaultvalue)
- 特殊令牌
- 无操作: _
所有这些功能都可以组合和嵌套:
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
详细语法,请参照官方!