Thymeleaf 在頁面中直接顯示內容
一般情況下 Thymeleaf 模板要輸出變量需要在某個標簽中(如<div>、<span>
)寫th:text
等屬性來實現。但有時我們希望想不寫在標簽中,直接輸出變量的值,比如在 <title>
標簽中直接顯示變量 msg
的值,而不需要包含在 <span>
等標簽中。
解決方案一:
使用 th:block
<title><th:block th:text="${msg}" /> - 服務器錯誤。</title>
參考:https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#synthetic-thblock-tag
解決方案二(推薦):
使用 inline
<title>[[${msg}]] - 服務器錯誤。</title> Hello, [[${user.name}]]! //[[]]寫法會html轉義 Hello, [(${user.name})]! //[()]寫法不會html轉義
參考:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#inlining
解決方案三:
使用 th:remove
<span th:text="${msg}" th:remove="tag"></span>