
Java | Thymeleaf | w3HexSchool
Thymeleaf Natural Templating
首先 我們知道 Thymeleaf 的綁定是用 th:xxx 來進行綁定的
像這樣:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Th Page</title> </head> <body> <p th:text="${helloMsg}"></p> </body> </html>
這樣我們在 respnse 中的 helloMsg 變數就會被後端渲染在頁面上了 ( 我的 helloMsg 內容是 “Hello Thymeleaf” )
渲染過後頁面是長這樣的:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Th Page</title> </head> <body> <p>Hello Thymeleaf</p> </body> </html>
他直接把我們的後端傳過來的內容渲染出來了
但是記得嗎?我們的 Thymeleaf 所使用的可是 HTML 檔案哦!
這代表瀏覽器是可以在沒有後端的環境下渲染畫面的!
來看一下我們在沒有後端的情況下直接讀取會怎樣
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Th Page</title> </head> <body> <p th:text="${helloMsg}"></p> </body> </html>
可以看到 th:text=”${helloMsg}” 是直接原封不動的傳給客戶端了 但是瀏覽器上看到是空白的,因為瀏覽器會自動忽視未定義的屬性 ( th:text 怎麽看到不像 HTML 定義過的屬性XD )
那這個時候我們再來對 <p> 標籤做一些改動:
<p th:text="${helloMsg}">What about us</p>
我們在標籤內加一些內容
看看在有無後端的環境下各會渲染出什麼樣子吧!
有後端解析
<!-- 略過... --> <p>Hello Thymeleaf</p> <!-- 略過... -->
可以看到有後端的狀況下看不出什麼差別
沒後端解析
<!-- 略過... --> <p th:text="${helloMsg}">What about us</p> <!-- 略過... -->
可以看到,一樣是照實渲染了頁面,不過這次在我們的瀏覽器上就看得到字,不再是一片空白了~

而這個特性呢!
就可以讓前端人員在使用與後端同一份檔案的情況下,不一定要依賴於後端的資源轉換
在 Thymeleaf 官方文件中稱其為 Natural Templating.
從 Thymeleaf 官網來的一段文字
This helps your designer and developer to work on the very same template file and reduce the effort required to transform a static prototype into a working template file. The ability to do this is a feature called Natural Templating.
No Comment