springboot模板技术Thymeleaf

清疚 2022-11-22 00:05 162阅读 0赞

Spring Boot框架对很多常用的模板引擎技术(如:FreeMarker、Thymeleaf、Mustache等)提供了整合支持,只需引入对应的起动依赖。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4. </dependency>

开发环境要修改配置

  1. // thymeleaf页面缓存设置(默认为true),开发中方便调试应设置为false,上线稳定后应保持默
  2. true
  3. 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、变量表达式${…}主要用于获取上下文中的变量值

  1. <p th:text="${title}">这是标题</p>

2、*{title} 选择变量表达式获取当前指定对象book的title属性值。

  1. <div th:object="${book}">
  2. <p>titile: <span th:text="*{title}">标题</span>.</p>
  3. </div>

3、定义首页尾页

  1. <div>
  2. <a th:href="@{${'/pageList'}(pageNum=1,pageSize=${pageSize})}">首页</a>
  3. <a th:href="@{${'/pageList'}(pageNum=${pageNum-1},pageSize=${pageSize})}">上一页</a>
  4. <a th:href="@{${'/pageList'}(pageNum=${pageNum+1},pageSize=${pageSize})}">下一页</a>
  5. <a th:href="@{${'/pageList'}(pageNum=${totalPage},pageSize=${pageSize})}">尾页</a>
  6. </div>

4、链接表达式@{…}一般用于页面跳转或者资源的引入

  1. <a th:href="@{/order/details(orderId=${o.id})}">view</a>

5、式~{…}用来标记一个片段模板,最常见的用法是使用th:insertth:replace属性插入片段

  1. <div th:insert="~{header::title}"></div>

发表评论

表情:
评论列表 (有 0 条评论,162人围观)

还没有评论,来说两句吧...

相关阅读