參考網址: https://blog.csdn.net/mlin_123/article/details/51816533css
1.1 Thymeleaf 在有網絡和無網絡的環境下皆可運行,並且徹底不需啓動WEB應用,即它可讓美工在瀏覽器查看頁面的靜態效果,也可讓程序員在服務器查看帶數據的動態頁面效果。
這是因爲它支持 html 原型,而後在 html 標籤裏增長額外的屬性來達到模板+數據的展現方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,因此 thymeleaf 的模板能夠靜態地運行;
當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。
1.2 Thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,能夠直接套用模板實現JSTL、 OGNL表達式效果,避免天天套模板、該jstl、改標籤的困擾。同時開發人員也能夠擴展和建立自定義的方言。
1.3 Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,能夠快速的實現表單綁定、屬性編輯器、國際化等功能。
相比於其餘的模板引擎,Thymeleaf最大的特色是經過HTML的標籤屬性渲染標籤內容,如下是一個Thymeleaf模板例子: <!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>
這是一段標準的HTML代碼,這也就意味着經過瀏覽器直接打開它是能夠正確解析它的結構並看到頁面的樣子。相比於其餘的模板引擎在指定的位置經過 ${} 等表達式進行渲染,Thymeleaf則是一種針對HTML/XML定製的模板語言(固然它能夠被擴展),它經過標籤中的th:text屬性來填充該標籤的一段內容。上例中, <p th:text="#home.welcome}" >Welcome to our grocery store!</p>
意味着<p>
標籤中的內容會被表達式 #{home.welcome} 的值所替代,不管模板中它的內容是什麼,之因此在模板中「畫蛇添足「地填充它的內容,徹底是爲了它可以做爲原型在瀏覽器中直接顯示出來。html
變量 Thymeleaf模板引擎在進行模板渲染時,還會附帶一個Context存放進行模板渲染的變量,在模板中定義的表達式本質上就是從Context中獲取對應的變量的值: <p>Today is: <span th:text="${today}">13 february 2011</span>.</p>假設today的值爲2016年7月14日,那麼渲染結果爲:<p>Today is: 2016年7月14日.</p>。
可見Thymeleaf的基本變量和JSP同樣,都使用${.}表示獲取變量的值。
url 處理 URL在Web應用模板中佔據着十分重要的地位,須要特別注意的是Thymeleaf對於URL的處理是經過語法@{…}來處理的。 Thymeleaf支持絕對路徑URL: <a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a> 同時也可以支持相對路徑URL: 1. 當前頁面相對路徑URL——user/login.html,一般不推薦這樣寫。 2. Context相關URL——/static/css/style.css 另外,若是須要Thymeleaf對URL進行渲染,那麼務必使用th:href,th:src等屬性,下面是一個例子: <!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) --> <a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
下面兩種url寫法是比較推薦使用的, <!-- Will produce '/order/details?orderId=3' (plus rewriting) --> <a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/order/3/details' (plus rewriting) --> <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a> 幾點說明: 上例中URL最後的(orderId=${o.id})表示將括號內的內容做爲URL參數處理,該語法避免使用字符串拼接,大大提升了可讀性, @{...}表達式中能夠經過{orderId}訪問Context中的orderId變量,
@{/order}是Context相關的相對路徑,在渲染時會自動添加上當前Web應用的Context名字,假設context名字爲app,那麼結果應該是/app/order
字符串替換 不少時候可能咱們只須要對一大段文字中的某一處地方進行替換,能夠經過字符串拼接操做完成:<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
一種更簡潔的方式是:<span th:text="|Welcome to our application, ${user.name}!|">, 固然這種形式限制比較多,|…|中只能包含變量表達式${…},不能包含其餘常量、條件表達式等。
運算符 在表達式中可使用各種算術運算符,例如+, -, *, /, % th:with="isEven=(${prodStat.count} % 2 == 0)" 邏輯運算符>, <, <=,>=,==,!=均可以使用,
>, <, >=, <= (gt, lt, ge, le)
== , != ( eq , ne )
gt
:great than(大於)>java
ge
:great equal(大於等於)>=程序員
eq
:equal(等於)==spring
lt
:less than(小於)<express
le
:less equal(小於等於)<=瀏覽器
ne
:not equal(不等於)!=服務器
惟一須要注意的是使用<,>時須要用它的HTML轉義符: th:if="${prodStat.count} gt 1" th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
循環
渲染列表數據是一種很是常見的場景,例如如今有n條記錄須要渲染成一個表格<table>,該數據集合必須是能夠遍歷的,使用th:each標籤: <body> <h1>Product list</h1> <table> <tr> <th>NAME</th> <th>PRICE</th> <th>IN STOCK</th> </tr> <tr th:each="prod : ${prods}"> <td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.inStock}? #{true} : #{false}">yes</td> </tr> </table> <p> <a href="../home.html" th:href="@{/}">Return to home</a> </p> </body> 能夠看到,須要在被循環渲染的元素(這裏是)中加入th:each標籤,其中th:each="prod : ${prods}"意味着對集合變量prods進行遍歷,循環變量是prod在循環體中能夠經過表達式訪問
條件求值 If/Unless Thymeleaf中使用th:if和th:unless屬性進行條件判斷,下面的例子中,<a>標籤只有在th:if中條件成立時才顯示:
<a th:href="@{/login}" th:if=${session.user != null}>Login</a> th:unless於th:if剛好相反,只有表達式中的條件不成立,纔會顯示其內容。 Switch Thymeleaf一樣支持多路選擇Switch結構: <div th:switch="${user.role}"> <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> </div> 默認屬性default能夠用*表示: <div th:switch="${user.role}"> <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> <p th:case="*">User is some other thing</p> </div>
Utilities 爲了模板更加易用,Thymeleaf還提供了一系列Utility對象(內置於Context中),能夠經過#直接訪問: - #dates - #calendars - #numbers - #strings - arrays - lists - sets - maps - … 下面用一段代碼來舉例一些經常使用的方法: #dates /* * Format date with the specified pattern * Also works with arrays, lists or sets */ ${#dates.format(date, 'dd/MMM/yyyy HH:mm')} ${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')} ${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')} ${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')} /* * Create a date (java.util.Date) object for the current date and time */ ${#dates.createNow()} /* * Create a date (java.util.Date) object for the current date (time set to 00:00) */ ${#dates.createToday()} #strings /* * Check whether a String is empty (or null). Performs a trim() operation before check * Also works with arrays, lists or sets */ ${#strings.isEmpty(name)} ${#strings.arrayIsEmpty(nameArr)} ${#strings.listIsEmpty(nameList)} ${#strings.setIsEmpty(nameSet)} /* * Check whether a String starts or ends with a fragment * Also works with arrays, lists or sets */ ${#strings.startsWith(name,'Don')} // also array*, list* and set* ${#strings.endsWith(name,endingFragment)} // also array*, list* and set* /* * Compute length * Also works with arrays, lists or sets */ ${#strings.length(str)} /* * Null-safe comparison and concatenation */ ${#strings.equals(str)} ${#strings.equalsIgnoreCase(str)} ${#strings.concat(str)} ${#strings.concatReplaceNulls(str)} /* * Random */ ${#strings.randomAlphanumeric(count)}
綜合實例 (參考網址: http://www.javashuo.com/article/p-boxudhmg-dg.html)
(thymeleaf手冊參考網址:https://blog.csdn.net/zrk1000/article/details/72667478)
迭代 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 1</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Answer for exercise 1: iteration</h1> <h2>Product list</h2> <table> <thead> <tr> <th>Description</th> <th>Price</th> <th>Available from</th> </tr> </thead> <tbody th:remove="all-but-first"> <tr th:each="product:${productList}"> <td th:text="${product.description}">Red Chair</td> <td th:text="${'$' + #numbers.formatDecimal(product.price, 1, 2)}">$123</td> <td th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</td> </tr> <tr> <td>White table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> <tr> <td>Reb table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> <tr> <td>Blue table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> </tbody> </table> </body> </html>
迭代統計<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 2</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Solution for exercise 2: iteration stats</h1> <h2>Product list</h2> <table> <thead> <tr> <th>Index</th> <th>Description</th> <th>Price</th> <th>Available from</th> </tr> </thead> <tbody th:remove="all-but-first">
<!--
index: 當前的索引,從0開始
count: 當前的索引,從1開始
size:總數
current:
even/odd:
first
last
-->
<tr th:each="product, productStat: ${productList}"> <td th:text="${productStat.count}">1</td> <!--注意這裏和上面的差異--> <td th:text="${product.description}">Red chair</td> <td th:text="${'$' + #numbers.formatDecimal(product.price, 1, 2)}">$350</td> <td th:text="${#dates.format(product.availableFrom, 'dd-MMM-yyyy')}">28-Jun-2013</td> </tr> <tr> <td>2</td> <td>White table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> <tr> <td>3</td> <td>Reb table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> <tr> <td>4</td> <td>Blue table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> </tbody> </table> </body> </html>
條件判斷
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 3</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Answer for exercise 3: conditions</h1> <h2>Product list</h2> <table> <thead> <tr> <th>Description</th> <th>Price</th> <th>Available from</th> <th></th> </tr> </thead> <tbody> <tr th:each="product : ${productList}"> <td th:text="${product.description}">Red chair</td> <td th:text="${'$' + #numbers.formatDecimal(product.price, 1, 2)}">$350</td> <td th:text="${#dates.format(product.availableFrom, 'dd-MMM-yyyy')}">28-Jun-2013</td> <td> <span th:if="${product.price lt 100}" class="offer">Special offer!</span> </td> </tr> </tbody> </table> </body> </html>
更多條件判斷
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 4</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Answer for exercise 4: more on conditions</h1> <h2>Customer list</h2> <table> <thead> <tr> <th>First name</th> <th>Last name</th> <th>Gender</th> <th>Payment method</th> <th>Balance</th> </tr> </thead> <tbody th:remove="all-but-first"> <tr th:each="customer : ${customerList}"> <td th:text="${customer.firstName}">Peter</td> <td th:text="${customer.lastName}">Jackson</td> <!-- Use th:switch for selecting content based on ${customer.gender}. As genre can be null if unknown, better use ${customer.gender?.name()} for obtaining its name. --> <td th:switch="${customer.gender?.name()}"> <img th:case="'MALE'" src="../../../images/male.png" th:src="@{/images/male.png}" alt="Male" /> <!-- Use "/images/male.png" image --> <img th:case="'FEMALE'" src="../../../images/female.png" th:src="@{/images/female.png}" alt="Female" /> <!-- Use "/images/female.png" image --> <span th:case="*">Unknown</span> </td> <td> <span th:text="${customer.paymentMethod.description}">Direct debit</span> <!-- Show next message only when paymentMethod is not CREDIT_CARD --> <span th:unless="${customer.paymentMethod.name() == 'CREDIT_CARD'}" class="warn"> Payment must be done in the next 4 days </span> </td> <!-- Add class="enhanced" when balance is greater than 10000 --> <td th:class="${customer.balance gt 10000} ? 'enhanced'" th:text="${customer.balance}">350</td> </tr> <tr> <td>Mary</td> <td>Johanson</td> <td><img src="../../../images/female.png" /></td> <td><span>Credit card</span></td> <td>5000</td> </tr> <tr> <td>Robert</td> <td>Allen</td> <td><img src="../../../images/male.png" /></td> <td> <span>Credit card</span> <span class="warn">Payment must be done in the next 4 days</span> </td> <td class="enhanced">50000</td> </tr> </tbody> </table> </body> </html>
Spring表達式語言
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 5</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Solution for exercise 5: Spring Expression language</h1> <h2>Arithmetic expressions</h2> <p class="label">Four multiplied by minus six multiplied by minus two module seven:</p> <p class="answer" th:text="${4 * -6 * -2 % 7}">123</p> <h2>Object navigation</h2> <p class="label">Description field of paymentMethod field of the third element of customerList bean:</p> <p class="answer" th:text="${customerList[2].paymentMethod.description}">Credit card</p> <h2>Object instantiation</h2> <p class="label">Current time milliseconds:</p> <p class="answer" th:text="${new java.util.Date().getTime()}">22-Jun-2013</p> <h2>T operator</h2> <p class="label">Random number:</p> <p class="answer" th:text="${T(java.lang.Math).random()}">123456</p> </body> </html>
超連接 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 6</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Answer for exercise 6: links</h1> <h2>Product actions</h2> <ul> <li><a href="#" th:href="@{/exercise11/product.html(action='view')}">View product</a></li> <li><a href="#" th:href="@{/exercise11/product.html(action='edit')}">Edit product</a></li> </ul> </body> </html>
表單 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 7</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Solution for exercise 7: forms</h1> <h2>Customer edition</h2> <form action="saveCustomer.html" th:action="@{/exercise12/saveCustomer.html}" th:object="${customer}" method="post"> <input type="hidden" th:field="*{id}" /> <label for="firstName">First name:</label> <input type="text" th:field="*{firstName}" value="John" /> <label for="lastName">Last name:</label> <input type="text" th:field="*{lastName}" value="Wayne" /> Genre: <div th:each="gender : ${genders}" class="radio"> <input type="radio" th:value="${gender}" th:field="*{gender}" /> <label th:for="${#ids.prev('gender')}" th:text="${gender.description}">Male</label> </div> <div th:remove="all" class="radio"> <input type="radio" /> <label>Female</label> </div> <label for="paymentMethod">Payment method:</label> <select th:field="*{paymentMethod}" th:remove="all-but-first"> <option th:each="paymentMethod : ${paymentMethods}" th:value="${paymentMethod}" th:text="${paymentMethod.description}">Credit card</option> <option>Another payment method</option> <option>Another payment method</option> </select> <label for="balance">Balance (dollars):</label> <input type="text" th:field="*{balance}" size="10" value="2500" /> <input type="submit" /> </form> </body> </html>
內聯 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 8</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Solution for exercise 8: inlining</h1> <h2>Birthday email</h2> <form action="#" method="post"> <label for="body">Message body:</label> <textarea id="body" name="body" th:inline="text"> Dear [[${customerName}]], it is our sincere pleasure to congratulate your in your birthday: Happy birthday [[${customerName}]]!!! See you soon, [[${customerName}]]. Regards, The Thymeleaf team </textarea> <input type="submit" value="Send mail" /> </form> </body> </html>
轉義和非轉義文本 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 9</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Solution for exercise 9: escaped and unescaped text</h1> <div th:text="${html}"> Some escaped text </div> <div th:utext="${html}"> Some unescaped text </div> </body> </html>
國際化 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title th:text="#{tutorial.exercise10}">Thymeleaf tutorial: exercise 10</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1 th:text="#{tutorial.exercise4}">Thymeleaf tutorial - Solution for exercise 10: internationalization</h1> <h2 th:text="#{product.info}">Product information</h2> <dl> <dt th:text="#{product.name}">Product name</dt> <dd th:text="${product.description}">Red chair</dd> <dt th:text="#{product.price}">Product price</dt> <dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">350</dd> <dt th:text="#{product.available}">Product available from</dt> <dd th:text="${#dates.format(product.availableFrom, 'dd-MMM-yyyy')}">28-Jun-2013</dd> </dl> </body> </html>
此時html須要相應的配置文件。例如以下配置文件: en: tutorial.exercise4=Thymeleaf tutorial - exercise 10: internationalization product.info=Product information product.name=Product name product.price=Product price product.available=Product available from back=Back
fr tutorial.exercise4=Tutorial De Thymeleaf - exercice 10: l'internationalisation product.info=Information du produit product.name=Nom du produit product.price=Prix du produit product.available=Produit disponible depuis back=Revenir
字符串拼接 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 11</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Answer for exercise 11: string concatenation</h1> <h2>Product information</h2> <dl> <dt>Product price</dt> <dd th:text="${'$'+product.price}">235</dd> </dl> </body> </html>
簡單數據轉換(數字,日期) <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 12</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Answer for exercise 12: bean values</h1> <h2>Product information</h2> <dl> <dt>Product name</dt> <dd th:text="${product.description}">red Chair</dd> <dt>Product price</dt> <dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">180</dd> <dt>Product available from</dt> <dd th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</dd> </dl> </body> </html>
bean值替換 <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf tutorial: exercise 13</title> <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" /> <meta charset="utf-8" /> </head> <body> <h1>Thymeleaf tutorial - Answer for exercise 13: bean values</h1> <h2>Product information</h2> <dl> <dt>Product name</dt> <dd th:text="${product.description}">Red Chair</dd> <dt>Product price</dt> <dd th:text="${product.price}">350</dd> <dt>Product available from</dt> <dd th:text="${product.availableFrom}">2014-12-01</dd> </dl> </body> </html>
https://www.cnblogs.com/asdop/p/6093599.html網絡
https://www.thymeleaf.org/session