springboot模板技术Thymeleaf
Spring Boot框架对很多常用的模板引擎技术(如:FreeMarker、Thymeleaf、Mustache等)提供了整合支持,只需引入对应的起动依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
开发环境要修改配置
// thymeleaf页面缓存设置(默认为true),开发中方便调试应设置为false,上线稳定后应保持默
认true
spring.thymeleaf.cache=false
Thymeleaf语法
th: | 标签 说明 |
---|---|
th:insert | 布局标签,替换内容到引入的文件 |
th:replace | 页面片段包含(类似JSP中的include标签) |
th:each | 元素遍历(类似JSP中的c:forEach标签) |
th:if | 条件判断,如果为真 |
th:unless | 条件判断,如果为假 |
th:switch | 条件判断,进行选择性匹配 |
th:case | 条件判断,进行选择性匹配 |
th:value | 属性值修改,指定标签属性值 |
th:href | 用于设定链接地址 |
th:src | 用于设定链接地址 |
th:text | 用于指定标签显示的文本内容 |
Thymeleaf表达式
说明 | 表达式语法 |
---|---|
变量表达式 | ${…} |
选择变量表达式 | *{…} |
消息表达式 | #{…} |
链接URL表达式 | @{…} |
片段表达式 | ~{…} |
示例
1、变量表达式${…}主要用于获取上下文中的变量值
<p th:text="${title}">这是标题</p>
2、*{title} 选择变量表达式获取当前指定对象book的title属性值。
<div th:object="${book}">
<p>titile: <span th:text="*{title}">标题</span>.</p>
</div>
3、定义首页尾页
<div>
<a th:href="@{${'/pageList'}(pageNum=1,pageSize=${pageSize})}">首页</a>
<a th:href="@{${'/pageList'}(pageNum=${pageNum-1},pageSize=${pageSize})}">上一页</a>
<a th:href="@{${'/pageList'}(pageNum=${pageNum+1},pageSize=${pageSize})}">下一页</a>
<a th:href="@{${'/pageList'}(pageNum=${totalPage},pageSize=${pageSize})}">尾页</a>
</div>
4、链接表达式@{…}一般用于页面跳转或者资源的引入
<a th:href="@{/order/details(orderId=${o.id})}">view</a>
5、式~{…}用来标记一个片段模板,最常见的用法是使用th:insert
或th:replace
属性插入片段
<div th:insert="~{header::title}"></div>
还没有评论,来说两句吧...