2020-07-26
JAVATHYMELEAF

Thymeleaf Natural Templating

Java Thymeleaf 伺服器端 HTML 模板引擎使用介紹。

Thymeleaf

Thymeleaf 是一個 Java 的伺服器端 HTML 模板引擎,他是一個完全可以取代 JSP 的存在,而且不管在有沒有網路的環境都是可以運行的。

首先,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 定義過的屬性 )


我們再來對 p 標籤做一些改動看看。

<p th:text="${helloMsg}">What about us</p>

在標籤內加一些內容。 看看在有無後端的環境下各會渲染出什麼樣子。

  • 有後端解析
<!-- 略過... -->
        <p>Hello Thymeleaf</p>
<!-- 略過... -->
  • 沒後端解析
<!-- 略過... -->
        <p th:text="${helloMsg}">What about us</p>
<!-- 略過... -->

可以看到,一樣是照實渲染了頁面,不過這次在我們的瀏覽器上就看得到字,不再是一片空白了。

這個特性就可以讓前端人員在使用與後端同一份檔案的情況下,不一定要依賴於後端的資源轉換。 在 Thymeleaf 官方文件中稱其為 Natural Templating.

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.