一.DOM元素
1 标准写法: <span th:text="${stu.id}"> </span>
2 内嵌式写法:由[[...]]包围一个表达式 <span> [[${stu.name}]] / Ch </span> <br>
3 混合写法:不常见,用 |…| 指定一个混合文本 <span th:text="| ${stu.cellphone} - 拨打 |">
- th:xxx 表示增加一个名为 xxx 的属性
例如 :
<div th:data=" ${stu.id} "></div> ,经 Thymeleaf 处理之后,得到 <div data="1000"></div>
属性的名称可以是现有的,如 th:class th:href 。也可以自定义的,如 th:data th:xyz th:role。
@Controller
public class TestController
{
@RequestMapping("info.do")
public String myTest(Model model)
{
Person p=new Person(100, "lihua", true);
model.addAttribute("person",p);
return "info";//全路径 /template/info.html,相关配置在spring-mvc.xml里
}
} <body>
<div th:data="${person.id}" th:class="${person.name}">
学号:<label th:text="${person.id}">0000</label><br />
姓名:<label>[[ ${person.name} ]] /CN</label><br />
姓名:<label th:text="|${person.name} -修改|"></label><br />
性别:<label th:text="${person.sex?'男':'女'}">0000</label><br />
</div>
</body>
二.URL
- Thymeleaf 中URL的写法: <img th:src=" @{/image/photo.jpg} " > 其中, @{ …} 用于表示一个URL,Thymeleaf会对其进行处理。
Thymeleaf的处理规则: @{/image/photo.jpg} -> /spring/image/photo.jpg 即,在前面自动添加了 Context-Path。
- 应用场景:
1 js 脚本的引入 <script th:src= … >
2 css脚本的引用 <link th:href= … >
3 超链接 <a th:href= … >
4 图片 <img th:src=… >
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>info</title>
<script th:src="@{/js/jquery.min.js}"></script>
</head>
<body>
<img th:src="@{/images/a.jpg}" />
</body>
</html>处理后:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>info</title>
<script src="/spring/js/jquery.min.js"></script>
</head>
<body>
<img src="/spring/images/a.jpg" />
</body>
</html>三.if与switch
Thymeleaf 中支持 if 判断, th:if = "${expr} ",并不支持 if … else …。switch 可以表示 if … else … 逻辑。
@Controller
public class TestController
{
@RequestMapping("info.do")
public String myTest(Model model)
{
model.addAttribute("isVip",false);
return "info";//全路径 /template/info.html,相关配置在spring-mvc.xml里
}
} <body>
<div th:if="${isVip}">尊敬的vip用户,欢迎观看</div>
<div th:if="${!isVip}">请先开通vip再观看</div>
<th:block th:switch="${isVip}">
<div th:case="true">
尊敬的vip用户,欢迎观看
</div>
<div th:case="false">
请先开通vip再观看
</div>
</th:block>
</body>其中 <th:block> 仅表示逻辑,不会输出到HTML中。
实际结果:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>info</title>
</head>
<body>
<div>请先开通vip再观看</div>
<div>
请先开通vip再观看
</div>
</body>
</html>四.代码包含 th:fragment
新建一个common.html,用th:fragment声明一个代码片段。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>公共页面包含html</title>
</head>
<body>
<!-- 公共页面引用 -->
<!--注意,这里必须用 <th:block>来包含。因为<head>里不允许出现<div>元素。 -->
<th:block th:fragment="imports">
<script th:src="@{/js/jquery.min.js}"></script>
</th:block>
<!-- 公共页面头部 -->
<div th:fragment="header(a)">
<div>页面头部</div>
<div>vip状态:[[${a}?'yes':'no']]</div>
</div>
<!-- 公共页面尾部 -->
<th:block th:fragment="footer">
<div>页面尾部</div>
</th:block>
</body>
</html>
使用:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>info</title>
<th:block th:include="~{common::imports}"></th:block>
</head>
<body>
<div th:include="~{common::header(${isVip})}"></div>
<div th:if="${isVip}">尊敬的vip用户,欢迎观看</div>
<div th:if="${!isVip}">请先开通vip再观看</div>
<th:block th:include="~{common::footer}"></th:block>
<!--其中,
th:include表示包含一个片段
~{} 表示片段的位置
common::header 里面的的common表示 /template/common.html,header表示片段的名称
-->
</body>
</html>生成的页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>info</title>
<script src="/spring/js/jquery.min.js"></script>
</head>
<body>
<div>
<div>页面头部</div>
<div>vip状态:no</div>
</div>
<div>请先开通vip再观看</div>
<div>页面尾部</div>
</body>
</html>- 声明参数
例如,在定义 fragment的时候,定义a,b两个参数
<div th:fragment="footer(a,b)">
<div style='padding:20px; margin-top:40px; '>
[[${a}]] , [[${b}]]
</div>
</div>
- 传参
在包含片段的时候,传入参数。例如,
<div th:insert=" ~{common::footer(${stu.id} ,${stu.name)}"></div>
- 几种包含方式
用 th:include / insert / replace 都可以包含一个片段,略有区别。
th:include表示将目标的内容插过来
th:insert表示将目标插在当前 <div> 下
th:replace 表示将目标直接替换本元素
- 纯JS和CSS代码也是可以包含的,如下所示定义一个片段,然后包含即可
<div th:fragment="your_script">
<script>
</script>
</div>
五.Thymeleaf:内置对象
内置对象: Thymeleaf 内置在 Model里的一些对象。
- 分为两类:
- 工具对象 Utility Objects
- 上下文对象 Context Objects
内置的工具对象提供一些小的工具方法 ,例如: 显示一个日期 <span th:text = " ${ today } "> </span> 默认的显示格式可能不符合要求。
使用内置工具进行格式化: <span th:text=" ${ #calendars.format(today, 'yyyy-MM-dd') }"> </span> ,调用#calendars.format( date,format)方法, 其中,#calendars是一个内置的工具对象。也可以自己格式化之后,再放到 Model 里。
@Controller
public class TestController
{
@RequestMapping("/info.do")
public String myTest(Model model)
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date d=new Date();
String timeStr=sdf.format(d);
model.addAttribute("today",timeStr);
return "info";//全路径 /template/info.html,相关配置在spring-mvc.xml里
}
}注意:
1 内置对象的名字以 # 开头
2 内置对象不是必需的 一般我们会把数据先处理好,然后再放到 Model 里
3 还有很多内置的工具对象 #dates, #calendars, #numbers, #strings, #arrays, #lists, #sets, #maps , …
- 上下文对象
上下文对象,也是内置对象
#request ,#response ,#session ,#servletContext ,还有 #ctx, #vars, #locale …等
使用示例: ${#request.getAttribute('foo')}, ${#request.getParameter('foo')} ,${#request.getContextPath()} … ${#session.getAttribute('foo')}, ${#session.id} ,${#session.lastAccessedTime}
@Controller
public class TestController
{
@RequestMapping("/info.do")
public String myTest(Model model,HttpSession session)
{
session.setAttribute("user", "li");
return "info";//全路径 /template/info.html,相关配置在spring-mvc.xml里
}
} <body>
当前用户:<label th:text="${#session.getAttribute('user')}">0000</label>
</body>另外几个特殊的对象:(没有#开头) ,例如:param ,session, application 。按官方文档的说法,这三个不是上下文对象,但也是自动加到Model里的。
示例: <span th:text=" ${ session.user }" ></span> 相当于 #session.getAttribute('user')
Thymeleaf嵌入JavaScript
- 在 JavaScript中,也可以嵌入 Thymeleaf 表达式。
1 声明 th:inline <script th:inline="javascript" > </script>
2 使用 [[ … ]] 嵌入表达式
- 以下类型可以在 JavaScript中显示: String, int ,Boolean, double 等基本类型 Map, List ,POJO ( 必须具有 Getter方法), JSONObject ,JSONArray
@Controller
public class TestController
{
@RequestMapping("/info.do")
public String myTest(Model model)
{
Person p=new Person(100, "lihua", true);
model.addAttribute("person", p); //POJO
Map<String,Object> user=new HashMap<>();
user.put("id", 101);
user.put("username", "lihua");
user.put("isVip", false);
model.addAttribute("user", user); //Map
model.addAttribute("version", "3.0.9"); //String
model.addAttribute("count",10); //int
JSONObject personJ=(JSONObject) JSON.toJSON(p);
model.addAttribute("personJ", personJ); // JSONObject(Map)
return "info";//全路径 /template/info.html,相关配置在spring-mvc.xml里
}
}模板注意:
1 必须添加 th:inline="javascript"
2 不要额外添加双引号 ,Thymeleaf 会自动按要求添加双引号。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>info</title>
<script th:src="@{/js/jquery.min.js}"></script>
</head>
<body>
姓名:<label class="name"></label>
<script th:inline="javascript">
var person=[[ ${person}]];
var user=[[${user}]];
var version=[[${version}]];//不用加""
var count=[[${count}]];
var personJ=[[ ${personJ}]];
$(".name").html(person.name);
</script>
</body>
</html>
生成的页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>info</title>
<script src="/spring/js/jquery.min.js"></script>
</head>
<body>
姓名:<label class="name"></label>
<script>
var person={"id":100,"name":"lihua","sex":true};
var user={"id":101,"isVip":false,"username":"lihua"};
var version="3.0.9";//不用加""
var count=10;
var personJ={"sex":true,"name":"lihua","id":100};
$(".name").html(person.name);
</script>
</body>
</html>