Thymeleaf代码片段引用
代码?段表达式是表示标记?段的简单?法,并将其移动到模板周围。这允许我们复制它们,将它们传递给其他模板作为参数,等等。
最常?的?法是使?th:insert或th:replace或th:include进??段插入
我们在想要抽取的代码的标签上添加这个属性th:fragment="topbar"
<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar"> <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]a> <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search"> <ul class="navbar-nav px-3"> <li class="nav-item text-nowrap"> <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">注销a> li> ul> nav>
然后要引用的话在对应页面th:replace="~{模版名::name}"
模版名就是抽取时的那个html页面的名字,thymeleaf会自动解析,name是刚刚抽取代码片段的名字,这里是topbar
<div th:replace="~{commons/commons::topbar}">div>
三种引入公共片段的th属性:
th:insert:将公共片段整个插入到声明引入的元素中
th:replace:将声明引入的元素替换为公共片段
th:include:将被引入的片段的内容包含进这个标签中
th:insert是最简单的:它将简单地插?指定宿主标签的标签体中。
th:replace实际上?指定的?段替换其宿主标签。
th:include类似于th:insert,?不是插??段,它只插?此?段的内容。
选中高亮显示
高亮就是 class 属性后面添加 active
<a class="nav-link active">a>
下面代码传递个active参数
<div th:replace="~{commons/commons::sidebar(active='main.html')}">div>
如果 active 的参数值为 main.html,则显示高亮,否则不显示
<a th:class="${active=='main.html'?'nav-link active':'nav-link'}" th:href="@{/index.html}">
循环遍历
用th:each标签
<tbody> <tr th:each="emp:${emps}"> <td th:text="${emp.getId()}">1,001td> <td th:text="${emp.getLastName()}">Loremtd> <td th:text="${emp.getEmail()}">ipsumtd> <td th:text="${emp.getGender()==0?'女':'男'}">dolortd> <td th:text="${emp.department.getDepartmentName()}">sittd> <td th:text="${#dates.format(emp.getBirth(),'yyyy-MM-dd HH:mm:ss')}">sittd> <td> <button class="btn btn-sm btn-primary">编辑button> <button class="btn btn-sm btn-danger">删除button> td> tr> tbody>