🌍
Thymeleaf - テキスト出力(text, utext)
Thymeleaf
- official site: https://www.thymeleaf.org/
- official mannual - 基本機能: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
- official mannual - Spring統合: https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html
Thymeleaf 依存性追加
spring bootを使用する場合build.gralde
に以下の内容を追加。
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
Thymeleaf 使用宣言
<html xmlns:th="http://www.thymeleaf.org">
基本表現式
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax
テキスト - text, utext
Thymeleafは基本的にHTMLタグの属性に機能を定義して動作します。HTMLのコンテンツにデータを出力する時はth:text
を使います。
th:text
HTMLタグの属性ではなくHTMLコンテンツ領域の中に直接データを出力するときは[[...]]
を使います。
[[...]]
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf</title>
</head>
<body>
<h1>Thymeleafテキスト出力</h1>
<ul>
<li>th:text使用
<span th:text="${data}"></span>
</li>
<li>コンテンツ領域の中に直接データを出力 = [[${data}]]</li>
</ul>
</body>
</html>
Escape
Web Browserは<
をHTMLタグの始まりだと認識します。よって<
をHTMLタグではなく文字として認識させる方法が必要になります。それをHTML Entityと呼びます。
HTMLで使うタグをHTML Entityに変更するのをEscape(エスケープ)と呼びます。
そしてThymeleafが提供するth:text
, [[...]]
は基本的にEscapeを提供します。
Unescape
Escapeを使いたくない場合
th:utext
[(...)]
Discussion