1、菜单栏抽取为单独页面
- <html xmlns:th="http://www.thymeleaf.org"> 使用thymeleaf引擎解析页面
- th:fragment="topBar" 声明为片段
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 顶部导航栏 -->
<div class="naviBar" th:fragment="topBar">
<div class="navi">
<img id="logo" th:src="@{/static/images/tlogo.png}"/>
<ul id="menu">
<li><a th:href="@{/code}" class="active" th:class="${activeUri=='code.html'?'active':'unactive'}">在售项目</a></li>
<li><a th:href="@{/booking}" class="active" th:class="${activeUri=='booking.html'?'active':'unactive'}">预定项目</a></li>
<li><a href="#">技术贴吧</a></li>
<li><a th:href="@{/mine}" class="active" th:class="${activeUri=='mine.html'?'active':'unactive'}">个人中心</a></li>
<li>
<div class="logout">
<a href="/logout">退出</a>
</div>
</li>
</ul>
</div>
</div>
<!-- 底部信息栏 -->
<div class="footerbar" th:fragment="footerBar">
<hr/>
© 2019 版权所有
</div>
</body>
</html>
2、其他页面引用上面声明的片段
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>源码栈</title>
<link rel="icon" type="image/x-icon" th:href="@{/static/images/logo.png}"/>
<link type="text/css" rel="styleSheet" href="../static/css/navi.css" />
<link type="text/css" rel="styleSheet" href="../static/css/code.css" />
<link type="text/css" rel="styleSheet" href="../static/css/element-ui-index.css" />
</head>
<body>
<!-- 顶部导航栏 -->
<div th:replace="~{navi :: topBar(activeUri='code.html')}"></div>
<!-- 主内容区 -->
<div class="mainCenter"></div>
<!-- 底部信息栏 -->
<div th:replace="~{navi :: footerBar}"></div>
<script type="text/javascript" src="../static/vue/vue.js"></script>
<script type="text/javascript" src="../static/vue/element-ui-index.js"></script>
<script type="text/javascript">
new Vue({
el:'#main',
});
</script>
</body>
</html>
- th:replace="~{navi :: topBar(activeUri='code.html')}" 引用声明过的片段,其中navi 为声明片段的文件名,topBar为声明的片段名,而(activeUri='code.html')为传递的参数。
- th:class="${activeUri=='code.html'?'active':'unactive'}",通过获取传递的参数给链接设置不同的class属性,以显示链接的选中样式。
效果图如下(css样式不贴了)
3、thymeleaf引入片段的方式有如下三种:
<!--声明片段-->
<div id="naviBar" th:fragment="copy">公共内容</div>
<!--引用片段的3中方式-->
<div id="mainDiv1" th:insert="footer :: copy"></div>
<div id="mainDiv2" th:replace="footer :: copy"></div>
<div id="mainDiv3" th:include="footer :: copy"></div>
区别是:
- insert:将id为naviBar的div插入到mainDiv1中,此时页面代码为
<div id="mainDiv1">
<div id="naviBar">公共内容</div>
</div>
- replace:将id为mainDiv2的div替换为naviBar,替换后mainDiv2就不存在了,此时页面代码为
<div id="naviBar">公共内容</div>
- include:只会将naviBar中的内容,即“公共内容”放入到mainDiv3中,而d为naviBar的div节点不会引入,此时页面代码为
<div id="mainDiv3">
公共内容
</div>