How to standardize the header and footer common to each html page in a web application created using Spring Boot and Thymeleaf
I will omit the Java side, but the layout of the template and static content looks like this.
dir
src/main/resources
├── static
│ ├── css
│ │ ├── common.css
│ │ └── top.css
│ └── js
│ └── datepicker.js
└── templates
├── common.html
└── index.html
When Spring Boot refers to CSS and JS files from HTML under templates
,
Since static
is the root directory, it is configured like this.
common.html
<html xmlns:th="http://www.thymeleaf.org">
<!-- (1)Fragment the head you want to share-->
<head th:fragment="meta_header(title,links,scripts)">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!-- (2)CSS to read in common/JS -->
<link rel="stylesheet" href="/css/common.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- (3)Title format-->
<title th:text="${title}+' | sample app'">Each page title| sample app</title>
<!-- (4)What is read uniquely to each view-->
<th:block th:replace="${links} ?: _" />
<th:block th:replace="${scripts} ?: _" />
</head>
<body>
<!-- (5)Fragment the parts you want to standardize in the body-->
<header th:fragment="header">
<h1><a th:href="@{'/'}">sample app</a></h1>
</header>
</body>
</html>
(1) Since the fragment name can take arguments, set title, links, scripts
as arguments.
(2) Describe the CSS / JS that is read in common on each page.
(3) Set the page title format to th: text =" "
using the argument title
(4) Insert the CSS / JS read on each page using th: replace
By using the unprocessed token (?: _
), If $ {links}
is null, then th: block
itself is absent.
(5) If there is something you want to make common in the body, use th: fragment
to make it into a part.
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!-- (1)Replace with common header-->
<head th:replace="common :: meta_header('top',~{::link},~{::script})">
<!-- (2)CSS to load unique to this page/JS -->
<link rel="stylesheet" th:href="@{/css/top.css}" />
<script type="text/javascript" th:src="@{/js/datepicker.js}"></script>
</head>
<body>
<!-- (3)Call common parts-->
<div th:replace="common :: header"></div>
<h2>top page</h2>
</body>
(1) Replace header
with the one defined in common.html
by passing an argument.
(2) Define a file to be read uniquely to this page (ʻindex.htmlin this sample) (3) Replace common parts with
th: replace =" page name :: fragment name "`
How to standardize header / footer in Spring Boot Tutorial: Using Thymeleaf
Recommended Posts