一. 回顾
前面学习了Day34——Restful实验要求,今天学习公共页抽取
二. 抽取公共代码
2.1 抽取代码语法
th:fragment="片段名"
,片段名随意取。- 在需要抽取公共代码的标签里,声明id属性,比如
<nav id="topbar">
2.2 引入公共代码的语法
语法:th:insert="~{ 模板名::片段名}"
或th:insert="~{模板名::选择器}"
。其中~{}
可以省略不写
有3种引入:
th:insert="片段名"
,它将公共代码放入到一对<div>
中,因此使用这种有时会给css布局带来影响th:replace="片段名"
,它将声明引入的元素替换为公共片段(即不会加在<div>
中的th:fragment
)th:include="片段名"
,把声明引入的元素 的标签去掉,然后将声明引入的元素 的内容包含进<div>
中
模板名根据thymeleaf的前后缀配置规则进行解析,比如在templates文件夹的dashboard.html中抽取公共代码,那么引入的时候就是th:insert=“~{ dashboard::片段名或选择器}”
2.3 例子
2种声明公共代码方法:
<!-- 声明公共代码-->
<footer th:fragment="copy">
© 2020 xxx shangcheng
</footer>
<!-- 或 -->
<footer id="foot">
© 2020 xxx shangcheng
</footer>
3种引入公共代码方法:假设前面声明的公共代码在footer.html中
<!-- 使用< 模板名::片段名> -->
<div th:insert="footer::copy"></div>
<div th:replace="footer::copy"></div>
<div th:include="footer::copy"></div>
<!-- 使用<模板名::选择器> -->
<div th:insert="footer::#foot"></div>
<div th:replace="footer::#foot"></div>
<div th:include="footer::#foot"></div>
引入的效果:
<!-- th:insert引入的效果 -->
<div>
<footer>
© 2020 xxx shangcheng
</footer>
</div>
<!-- th:replace引入的效果 -->
<footer>
© 2020 xxx shangcheng
</footer>
<!-- th:include引入的效果 -->
<div>
© 2020 xxx shangcheng
</div>
三. 员工列表公共页抽取
3.1 需求
点击dashboard.html的侧边栏的员工管理能跳转到list.html,并抽取dashboard.html的顶部栏以及侧边栏的公共代码,在list.html中引入
3.2 效果
3.3 步骤
设置“员工管理”的请求地址为@{/emps}
<a class="nav-link" href="#" th:href="@{/emps}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
<circle cx="9" cy="7" r="4"></circle>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
<path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
</svg>
员工管理
</a>
写controller,使得点击dashboard.html的侧边栏的员工管理能跳转到list.html,如下:
package com.atguigu.springboot.controller;
import com.atguigu.springboot.dao.EmployeeDao;
import com.atguigu.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Collection;
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
@GetMapping(value="/emps")
public String list(Model model){
Collection<Employee> employees = employeeDao.getAll();
model.addAttribute("emps", employees);
return "emp/list";
}
}
抽取顶部栏以及侧边栏,如下:
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
<nav class="col-md-2 d-none d-md-block bg-light sidebar" id="sidebar">
在list.html删除公共代码片段,并引入公共代码,如下:
<!--引入顶部栏抽取的topbar-->
<!-- 模板名是根据thymeleaf的前后缀配置规则进行解析的 -->
<div th:replace="~{ dashboard::topbar}"></div>
<!--引入侧边栏-->
<div th:insert="~{dashboard::#sidebar}"></div>
每次修改完html页面,都可以按ctrl+F9来编译,使得无需重启程序就可以刷新页面