Thymeleaf 语法:
-
变量表达式:
- 变量表达式即 OGNL 表达式或 Spring EL 表达式(在 Spring 属性中也叫 model attributes)
- 如:$(session.user.name)
- 示例:<span th:text="${book.author.name}">
-
选择(星号)表达式:
- 选择表达式很像变量表达式,不过他们用一个预先选择的对象来代替上下问变量容器(map)
- 如:*{customer.name}
- 被指定的 object 由 th:object 属性定义:
<div th:object="${book}"> <span th:text="*{title}">··········</span> </div>
-
文字国际化表达式:
- 文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties),用 key 索引 Value,还可以提供一组参数(可选)
- 如:#{main.title}
-
URL 表达式:
- URL 表达式指的是把一个有用的上下文或回话信息添加到 URL,这个了过程经常被叫做 URL 重写。不需要指定项目名字
- 如:@{/hello/index}
- URL 还可以设置参数:
- @{/hello/details(id=${orserId})}
- 示例:
<form th:action="@{/hello}"> <a href="main.html" rel="external nofollow" th:href="@{/main}" rel="external">
表达式支持的语法:
-
字面:
- 文本文字:'one text','Another one! ',···
- 数字文本:1,2,3,4,···
- 布尔文本:true,false
- 空:null
- 文字标记:one,sometext,main,···
-
文本操作:
- 字符串连接:+
- 文本替换:| The name is ${name} |
-
算数运算:
- 二元运算:+ - * / %
-
布尔运算:
- 二元运算:and,or
- 布尔否定:!,not
-
比较和等价:
- 比较: <,>,<=,>=
- 等值运算符:==,!=
-
条件运算符:
- if-the:( if) ? (then)
- if-then-else:(if) ?(then) :(else)
- default:(value) ?:(defaultvalue)
-
示例:
'user is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
-
常用的 thymeleaf 标签:
- 标签检测:
- 模板:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <title>Title</title> </head> <body> <div th:text="${hello}" th:id="${hello.toUpperCase()}">xxxx</div> <input th:value="${user.getUsername()}"> <hr> <div th:object="${user}"> <span th:text="*{username}"></span> </div> <a th:href="" th:if="${user.getAge() == 2}" >年龄</a> <a th:class="${user.getAge() > 2}?'class1':'class2'" >年龄</a> <p th:if="${user.score >= 60 and user.score < 85}">B</p> <p th:if="${user.score < 60}">C</p> <p th:if="${user.score > 85}">优秀</p> <span th:switch="${user.gender}"> <p th:case="1">男</p> <p th:case="2">女</p> </span> <table> <tr th:each="a,aState:${uList}"> <td th:text="${a.username}"></td> <td th:text="${a.password}"></td> <td th:text="${aState.index}"></td> </tr> </table> </body> </html>
- Controller 层:
java">@Controller public class HelloController { @RequestMapping("/success") public String sayHello(HttpServletRequest request, HttpServletResponse response, Model model){ model.addAttribute("hello","任亮"); User user = new User(); user.setPassword("111"); user.setUsername("renliang"); user.setAge(11); user.setScore(33.0); user.setGender(2); List<User> list = new ArrayList<>(); for(int i = 0;i<10;i++){ User u = new User(); u.setUsername("张三"+1); u.setUsername("111" + i); list.add(u); } model.addAttribute("user",user); model.addAttribute("list",list); return "success"; } }
- 模板: