thymeleaf's layout is commonly used in two ways
The first
Divide each part of the page into 块
-> fragment
use th:include
and th:replace
to introduce the page
This usage has no concept of layout, because each part is fragment
, the following example illustrates
<!-- index.html -->
<html>
<head>
<meta charset="utf-8"/>
<title>demo</title>
</head>
<body>
<div th:include="components/header :: header"></div>
<div class="container">
<h1>hello world</h1>
</div>
<div th:include="components/footer :: footer"></div>
</body>
</html>
<!-- components/header.html -->
<header th:fragment="header">
<ul>
<li>news</li>
<li>blog</li>
<li>post</li>
</ul>
</header>
<!-- components/footer.html -->
<header th:fragment="footer">
<div>i am footer.</div>
</header>
The above example uses is , that is, the meaning of importing the th:include
definition , and the other is , which means to replace this part of the code in the current page, the following example illustratesfragment
th:replace
<html>
<head>
<meta charset="utf-8"/>
<title>demo</title>
</head>
<body>
<div th:replace="components/header :: header">
<!-- 使用th:replace进来的header.html会替换下面的这个header -->
<header>
<ul>
<li>static - news</li>
<li>static - blog</li>
<li>static - post</li>
</ul>
</header>
</div>
<div class="container">
<h1>hello world</h1>
</div>
<div th:include="components/footer :: footer"></div>
</body>
</html>
the second
Write a layout.html page as the base page of the page
<!-- layout/layout.html -->
<html>
<head>
<meta charset="utf-8"/>
<title>demo</title>
</head>
<body>
<div th:include="components/header :: header"></div>
<div layout:fragment="content"></div>
<div th:include="components/footer :: footer"></div>
</body>
</html>
Used in subpages layout:decorator
to add the content of subpages to layout.html
<!-- index.html -->
<html layout:decorator="layout/layout">
<head>...</head>
<body>
<div layout:fragment="content">
<h2>hello world!!!</h2>
</div>
</body>
</html>
In this way, the css, js, and imgs introduced in layout.html can be used in the sub-page, and the css, js, and imgs that the sub-page needs to use can also be introduced in the sub-page, which is very convenient and recommended.
template pass by value
If you want to pass a tab into header.html to distinguish which menu should be highlighted, you can use the following writing method to achieve
Set a style
.active {
background-color: green;
}
<header th:fragment="header (tab)">
<ul>
<li><span th:class="${tab eq 'news'} ? active">news</span></li>
<li><span th:class="${tab eq 'blog'} ? active">blog</span></li>
<li><span th:class="${tab eq 'post'} ? active">post</span></li>
</ul>
</header>
call writing
<div th:include="components/header :: header(tab='blog')"></div>
Related Links:
http://www.thymeleaf.org/doc/articles/layouts.html
END
Original link: https://tomoya92.github.io/2017/03/09/thymeleaf-layout/