博主
258
258
258
258
专辑

第六节 Thymeleaf模版指令:布局(Layout)

亮子 2022-02-16 00:27:52 6480 0 0 0

大多数的网站都有导航、底部等公共的东西,在一个网站里访问页面总是会显示相同的导航、底部之类的内容,layout解决的是模板复用的问题,比如常见的网站是下面这样的

我们推荐使用th:include + th:replace 方案来完成布局的开发

代码实现:
layout.html


<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>布局</title> <style> .header {background-color: #f5f5f5;padding: 20px;} .header a {padding: 0 20px;} .container {padding: 20px;margin:20px auto;} .footer {height: 40px;background-color: #f5f5f5;border-top: 1px solid #ddd;padding: 20px;} </style> </head> <body> <header class="header"> <div> <a href="/book/list.html">图书管理</a> <a href="/user/list.html">用户管理</a> </div> </header> <div class="container" th:include="::content">页面正文内容</div> <footer class="footer"> <div> <p style="float: left">&copy; heerh.com 2017</p> <p style="float: right"> Powered by god666hrh </p> </div> </footer> </body> user/list.html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" th:replace="layout"> <div th:fragment="content"> <h2>用户列表</h2> <div> <a href="/user/add.html">添加用户</a> </div> <table> <thead> <tr> <th> 用户名称 </th> <th> 用户年龄 </th> <th> 用户邮箱 </th> </tr> </thead> <tbody> <tr th:each="user : ${users}"> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> <td th:text="${user.email}"></td> </tr> </tbody> </table> </div> </html>

总结:

1.在layout页面需要渲染的标签加th:include=“::content”
2.在子页面的标签里加th:replace=“layout”,在渲染内容的标签里加th:fragment=“content”,目的是为了和公共页面(layout)里的标签内容对应上。

小技巧:
由于超链接有默认的打开链接行为,所以对于想要执行onclick 的时候,我们一般设置href=“javascript:;”
使用thymeleaf进行数字循环

需求:使用thymeleaf模版 根据一个数字在页面循环生成固定的标签
解决方案:需要用到thymeleaf 的#numbers.sequence()函数

示例:

<span th:each="i:${#numbers.sequence(1, 5)}">
   <span th:text="${i}"></span>
</span>

效果如下:

1 2 3 4 5