Thymeleaf笔记

Thymeleaf

Thymeleaf 是一种类似于jsp的动态网页技术

1、Thymeleaf 简介
  • jsp 必须依赖 Tomcat 运行、不能直接运行在浏览器中
  • HTML 可以直接运行在浏览器,但是不能接收控制器传递的数据
  • Thymeleaf 既保留了HTML的后缀能直接在浏览器运行的能力、又实现了jsp显示动态数据的功能
2、Thymeleaf 的导入

SpringBoot应用对 Thymeleaf 提供了良好的支持

1、添加 Thymeleaf 的 starter
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、创建 Thymeleaf 模板

Thymeleaf 模板就是HTML文件

  • SpringBoot应用中resources\templates目录就是用来存放页面模板的

注意:

  1. static 目录下的资源被定义为静态资源,SpringBoot应用默认放行;如果将 HTML 页面放在 static 目录下是可以直接访问的。
  2. templates 目录下的文件会被定义为动态网页模板,SpringBoot 应用会拦截 templates 中的静态资源;如果将 HTML 文件定义在 templates 目录,则必须通过控制器跳转访问。
3、HTML 引入 Thymeleaf
<html lang="en" xmlns:th="http://www.thymeleaf.org">

使用 Thymeleaf

eg:

<label th:text="${book.bookName}">图书名称</label>
3、Thymeleaf 的使用
1、引入命名空间
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>
2、th:text

将接收到的数据显示到标签的内容中

价格:<label th:text="${price}"></label><br>
字符串:<div th:text="${str}"></div><br>
<p th:text="${book.bookAuthor}">图书名称</p><br>
3、th:inline 内联
  • HTML 内联
<p th:inline="text">图书名称:[[${book.bookName}]]</p><br>
4、th:object 和 *
<div th:object="${book}">
    <p th:text="*{bookId}"></p>
    <p th:text="*{bookName}"></p>
    <p th:text="*{bookAuthor}"></p>
</div>
4、流程控制
1、th:each 循环
<table style="width: 600px" border="1" cellspacing="0">
    <caption>图书列表信息</caption>
    <thead>
        <tr>
            <th>图书ID</th>
            <th>图书名称</th>
            <th>作者</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="b:${books}">
            <td th:text="${b.bookId}"></td>
            <td th:text="${b.bookName}"></td>
            <td th:text="${b.bookAuthor}"></td>
        </tr>
    </tbody>
</table>
2、分支
  • th:if 如果条件不成立,则不显示此标签

    <td th:if="${b.bookPrice}>40" style="color: red">太贵!</td>
    <td th:if="${b.bookPrice}<=40" style="color: green">价格合理</td>
    
  • th:switch 和 th:case

5、碎片的使用

碎片就是 HTML 片段,我们可以将多个页面中使用的相同的 HTML 标签部分单独定义,然后通过 th:include 可以在 HTML 网页中引入定义的碎片

在这里插入图片描述

  • 定义碎片 th:fragment

  • 引用碎片 th:include(无样式) 和 th:replace(有样式)

    • a.html

      <!-- <div th:include="header::fragment1"></div> -->
      <div th:replace="header::fragment1"></div>
      
      <div th:replace="footer::fragment2">
          
      </div>
      
-->
<div th:replace="footer::fragment2">
    
</div>
```
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值