yucatio@システムエンジニア

趣味で作ったものいろいろ

『Spring Framework 超入門』のレイアウト化の作成がうまく出てこないときの対処法

Spring Framework超入門 ~やさしくわかるWebアプリ開発~』を読んでいます。


問題発生

6章の「レイアウト化の作成」のコードがうまく動きませんでした。

pageA.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="~{commons/layout}">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  <div layout:fragment="content">
    <h1>Page A</h1>
  </div>
</body>
</html>

期待したページ

f:id:yucatio:20220209225619p:plain

実際に表示されたページ

f:id:yucatio:20220209225632p:plain

共通レイアウトであるcommons/layoutが読み込まれていません。

Spring-bootのバージョンは2.6.3です。

対応方法

4行目のlayout:decoratorlayout:decorateにします。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{commons/layout}">

原因

  • Spring boot 2.6からthymeleaf-layout-dialectのバージョン3を使うことになりました。

github.com

  • thymeleaf-layout-dialectのバージョン3でlayout:decoratorが廃止されました。

ultraq.github.io

という2つの要因が重なって動かなかったわけです。Spring boot 2.5まではサンプルコードのままで動くはずです。