Thymeleaf中提供了一套标准方言,这种方言提供了各种处理器,这些处理器可以应用特定的逻辑到某个组件(标签、文本、注释等)对象。并且,对于大多数用户来说,这套标准方言足以满足各种逻辑表达的需求。
官方提供的Thymeleaf-spring方言,可以刚好地利用spring framework中的一些特性。例如,使用Spring Expression Language 或者Spring EL 代替OGNL。
这些标准方言里的处理器,都属于属性处理器,这使得浏览器在处理之前也能正确显示HTML模板文件内容,因为对于未定义的额外属性,会被直接忽略。这样可以帮助设计人员和开发人员使用完全相同的模板文件,减少将静态原型转换为工作模板文件所需的各项工作。我们称此为:自然模板。
这里将从一下几个方面介绍Thymeleaf的基本语法:
- Thymeleaf 表达式
- Thymeleaf支持的字面值
- Thymeleaf支持的运算
- Thymeleaf常用的th:*属性
- Thymeleaf表达式基本对象
- Thymeleaf表达式工具对象
Thymeleaf 表达式
作为Thymeleaf标准方言最重要的组成部分,Thymeleaf提供了各种表达式,用于定制和现实不同类型的内容。
- 变量表达式 ${...}
- 选择变量表达式(星号表达式)*{...}
- 消息表达式 #{...}
- URL链接表达式 @{...}
- 片段表达式 ~{...}
变量表达式 ${...}
变量表达式用于显示某个变量的值,可以是普通表达式的计算结果,或者是服务器端返回的某个属性的值。
例如:
在ThymeleafController.java中添加以下代码,用于返回数据到视图
/**
* 这里我们需要使用@Controller注解:因为这个类返回的是视图(View)而不是数据(Data)
*/
@Controller
public class ThymeleafController {
@GetMapping("/index")
public String index(Model model, HttpSession session){
//在model中来存放要返回给客户端的数据key:value,在客户端中通过key获取对应的value
model.addAttribute("message","Hello World!!!");
model.addAttribute("result",100+200);
model.addAttribute("user",new User("alice",123456L,"email","M"));
session.setAttribute("user2",new User("admin",987654L,"[email protected]","L"));
return "index";//逻辑视图名
}
}
在index.html模板中添加变量表达式显示各种数据
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${message}">Hi</h1>
<h1 th:text="${result}">计算结果</h1>
<h1 th:text="${1>2}">计算结果</h1>
<h1 th:text="${10*20}">计算结果</h1>
<div>
<h1 th:text="${user}">user对象</h1>
<h1 th:text="${user.username}">显示用户名</h1>
<h1 th:text="${user.pwd}">显示用户密码</h1>
</div>
<div>
<h1 th:text="${session.user2}">显示session作用域中的user2对象</h1>
<h1 th:text="${session.user2.username}">显示session作用域中的user2对象的用户名</h1>