Thymeleaf 在模板頁面除了th:text標籤屬性搭配${...}帶入變數外,還可使用行內表示式[[...]]或[(...)]帶入變數。
例如在「Spring Boot Thymeleaf 簡單範例的hello.html中使用標籤屬性th:text帶出${name}的值。
修改hello.html如下。
第一個<p>的文字中帶入變數的方式是以行內標籤例如<span>加上th:text="{...}"來帶入。
第二個<p>改用行內表示式[[${...}]]帶入變數。
hello.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello Thymeleaf</title>
</head>
<body>
<p>Hello <span th:text="${name}"></span>! How are you doing?</p><!-- tag attribute -->
<p>Hello [[${name}]]! How are you doing?</p><!-- inlined expressions -->
</body>
</html>
啟動專案在瀏覽器輸入http://localhost:8080/demo/hello?name=John返回的html如下。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello Thymeleaf</title>
</head>
<body>
<p>Hello <span>John</span>! How are you doing?</p><!-- tag attribute -->
<p>Hello John! How are you doing?</p><!-- inlined expressions -->
</body>
</html>
[[...]]相當於th:text會跳脫HTML符號(e.g. <、>、&、"...):
[(...)]相當於th:utext不會跳脫HTML符號。
如果要停用此功能,則在標籤使用th:inline="none"。例如在hello.html第二個<p>加上th:inline="none"如下。
hello.html
...
<p th:inline="none">Hello [[${name}]]! How are you doing?</p>
...
回應html如下。
...
<p>Hello [[${name}]]! How are you doing?</p>
...
行內表示式也能在<script>的JavaScript中使用,此功能必須在<script>加上th:inline="javascript"啟用。
在hello.html加入<script th:inline="javascript">來啟用JavaScript的行內表示式如下。
hello.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello Thymeleaf</title>
</head>
<body>
<p>Hello <span th:text="${name}"></span>! How are you doing?</p><!-- tag attribute -->
<p>Hello [[${name}]]! How are you doing?</p><!-- inlined expressions -->
<script th:inline="javascript">// enable JavaScript inlining
var name = [[${name}]]; // JavaScript inlining
alert(name);
</script>
</body>
</html>
重新啟動專案在瀏覽器輸入http://localhost:8080/demo/hello?name=John返回的html如下。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello Thymeleaf</title>
</head>
<body>
<p>Hello <span>John</span>! How are you doing?</p><!-- tag attribute -->
<p>Hello John! How are you doing?</p><!-- inlined expressions -->
<script>
var name = "John"; // 帶入${name}的值且自動以雙引號""包起
alert(name);
</script>
</body>
</html>
CSS則在<style>加上th:inline="css"來啟用行內表示式。
<style th:inline="css">
.[[${classname}]] {
text-align: [[${align}]];
}
</style>
沒有留言:
張貼留言