- _nosay
Thymeleaf
2018-05-07 10:57:15
理解 Thymeleaf
- Java 模板引擎。能够处理 HTML,XML,JavaScript,CSS甚至纯文本。类似JSP,Freemarker。
- 自然模板,原型即页面。
- 语法优雅易懂,OGNL,SpringEL。
- 遵从 Web 标准,支持HTML5。
Thymeleaf 标准方言
- <span th:text="...">
- <span data-th-text="...">
例子:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Good Thymes Virtual Grocery</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" type=text/css" media="all" href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
</head>
<body>
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
</body>
</html>
它能做什么
标准表达式
- 语法: ${...}
<span th:text="${book.author.name}" >
消息表达式
- 语法: #{...}
<span th:text="#{book.author.name}" >
- 也称为文本外部化,国际化或i18n
选择表达式
- 语法: *{...}
<div th:object="${book}"> <span th:text="*{title}">...</span> </div>
- 与变量表达式的区别:它们是在当前选择的对象而不是整个上下文变量映射上执行
链接表达式
- 语法: @{...}
链接表达式可以是相对的,在这种情况下,应用程序上下文将不会作为URL前缀:
<a th:href="@{../documents/report}">...</a>
也可以是服务器相对(同样,没有应用程序上下文前缀)
<a th:href="@{~/contents/main}">...</a>
和协议相对(就像绝对URL,但浏览器将使用在显示的页面中使用的相同的HTTP或HTTPS协议)
<a th:href="@{//static.mycompany.com/res/initial}">...</a>
当然,Link表达式可以是绝对的:
<a th:href="@{http://www.mycompany.com/main}">...</a>
分段表达式
- 语法: th:insert或th:replace
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <div th:insert="~(footer :: copy)"></div> </body> </html>
文本
- 文本
<p> Now you are looking at a <span th:text="'working web application'">template file</span> </p>
- 数字
<p>The year is <span th:text="2013">1492</span></p> <p>In two years,it will be <span th:text:="2013+2">1492</span></p>
- 布尔
<div th:if="${user.isAdmin()} == false"> ... </div>
- 算术操作(+,-,*,/,%)
<div th:with="isEven=(${prodStat.count}%2 == 0)">
比较和等价
比较:>,<,>=,<=(gt,lt,ge,le)
<ul class="pagination" data-th-if="${page.totalPages le 7}" >
等价:==,!=(eq,ne)
<option data-th-each="i: $(#arrays.toIntegerArray({5,10,40,100}))" data-th-value="${i}" data-th-selected="${i eq page.size}" data-th-text="${i}"></option>
- 条件运算符
<tr th:class="${row.even}? 'even':'odd'"> ... </tr>
- 无操作
<span th:text="${user.name}?:_">no user authenticated</span>
设置属性值
设置任意属性值 th:attr<form action="subscribe.html" th:attr="action=@{/subscribe}"> <fieldset> <input type="text" name="email" /> <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}" /> </fieldset> </form>