创建控制器

@GetMapping("/p7")
public void p7(Model model, HttpServletRequest req) {
    User user = new User();
    user.setUsername("P7");
    user.setDate(new Date());
    model.addAttribute("user",user);
}

创建组件

创建templates/component/p7.html,内容如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="<http://www.thymeleaf.org>">
<head>
</head>

<div th:fragment="header">
    <div style="height: 100px; background-color: gold">
        <!--/*@thymesVar id="user" type="com.example.thymeleaf.entity.User"*/-->
        <h1 th:text="${user.username}"></h1>
    </div>
</div>

<div th:fragment="body(message)">
    <div style="height: 100px; background-color: yellowgreen">
        <h1>I'am Body</h1>
    </div>
    <div th:replace="${message}"></div>
</div>

</html>

创建templates/p7.html,作为最终渲染的页面,内容如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="<http://www.thymeleaf.org>">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div th:insert="component/p7::header"></div>

<div th:insert="component/p7::body( ~{::#body} )">
    <div id="body">
        <h1 style="color: yellowgreen">我才是真正的Man</h1>
    </div>
</div>

</body>
</html>