Thymeleafのチートシート
どんどん追加していきます
■条件分岐
「errorMessage」がnullでないときは「エラー」を出力
<p th:if="${errorMessage != null}">エラー</p>
■要素がないときに表示させる
<div th:if="${#lists.isEmpty(hogeList)}">
<p>要素がありません</p>
</div>
■多項分岐
th:switchが使える。どこにも一致しなければth:case="*"となる(javaでいうdefaultみたいなもの)
<div th:switch="${month}">
<p th:case="1" th:text="|${month}月|"></p>
<p th:case="2" th:text="|${month}月|"></p>
<p th:case="3" th:text="|${month}月|"></p>
<p th:case="*">対象なし</p>
</div>
■ if、unless
<!-- 【条件】ID=1の場合に表示 -->
<div th:if="${hoge.id==1}">
<p>hogeのid(ID=1)の場合に表示します</p>
</div>
<!-- 【条件】ID=1以外の場合に表示 -->
<div th:unless="${hoge.id==1}">
<p>hogeのidが(ID=1)以外の場合に表示します</p>
</div>
404に遷移
@GetMapping("hoge/1")
public void getHoge(){
System.out.println("404ページに遷移します");
throw new ResourceNotFoundException();
}
省略
与えられたテキストが最大サイズnになるよう省略処理をして最後に "..." がつきます。
${#strings.abbreviate(str,10)}//7文字+…(だったと思います)
省略&改行コードを削除
<p th:utext="${#strings.abbreviate(#strings.replace(hoge.message, '<br />', ''), 40)}"></p>
messages.propertiesを使ってインクルード化したタイトルやmetaを管理する用法
headタグを全ファイル共通化した上で、タイトルやディスクリプションなどをmessages.propertiesに記述する場合の書き方です。
resourcesフォルダ配下にmessages.propertiesを作成
head:
title:
top: "トップページ"
categoryTop: "カテゴリのトップページ"
categoryDetail: "カテゴリの詳細ページ"
description:
top: "トップページの説明です"
categoryTop: "カテゴリのトップページの説明です"
categoryDetail: "カテゴリの詳細ページの説明です"
url:
top: "hoge/index.html"
categoryTop: "hoge/category/index.html"
categoryDetail: "hoge/category/detail.html"
html側
<title th:text="#{head.title.__${var}__}"></title>
<meta name="description" th:content="#{head.description.__${var}__}">
var=top ← 「top」部分にページ毎に割り振った変数名を記述(propertiesと同一にする)
<head>
<div th:with="var=top"></div>
<div th:replace="inc-head"></div>
</head>
var=categoryTop ← 「categoryTop」部分にページ毎に割り振った変数名を記述(propertiesと同一にする)
<head>
<div th:with="var=categoryTop"></div>
<div th:replace="inc-head"></div>
</head>
__${変数}__
プリプロセッシング
__${変数}__
で宣言することで事前に評価される。
th:replace
インクルード化する時に使用
th:with
変数を使う時に使用
リンク
Thymeleafの標準式構文 | Java好き
https://javazuki.com/articles/thymeleaf-standard-expression-syntax.html
「Thymeleaf」のth:xxxx=""の属性に何が書けるのかという構文の話。 Table of Contents. 前提; 単純式. 変数式; 選択変数式; リンクURL式. リテラル; 演算 ...
タイムリーフ Tutorial: Using Thymeleaf (ja)