thymeleaf零碎知识点

本文介绍了如何在SpringBoot项目中使用Thymeleaf,强调了必须导入相关依赖。Thymeleaf动态属性的实现方式是在HTML标签后添加`th:xxx`,并用`@`或`$`结合表达式插入动态内容。同时,讲解了如何在纯文本中插入动态文本。此外,还展示了Thymeleaf如何抽取和使用公共代码,通过`th:fragment`或ID选择器实现。最后,文章提到了Thymeleaf的遍历功能,用于将控制器传递的数组或集合内容展示在表格中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 首先如果在SpringBoot项目中使用thymeleaf,必须在pom.xml文件中导入相应的依赖
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
    
  • thymeleaf是针对于HTML页面的如果想让thymeleaf语法在页面中正常的使用,就必须在提前告知该HTML页面是用了该语法。
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
     该句代码后面的xmlns:th="http://www.thymeleaf.org"就是告知页面使用thymeleaf
    
  • 如果想把标签中的某个属性变成动态属性,在这个属性的后面再加一个th:xxx,xxx为动态属性的名称,然后在双引号中加入@或者$然后在大括号中加入要更改的内容。
    <label style="color: red" th:text="${msg}"></label>
    
  • 如果在纯文本中加入加入动态文本,则是先加两个中,在中口号中加入${对应的内容}
    <a href="#" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
      <img src="images/photos/user-avatar.png" alt="" />
      [[${session.loginUser.userName}]]
      <span class="caret"></span>
    </a>
    
  • thymeleaf抽取公共代码
    • 如果要抽取代码首先得有一个公共的HTML文件来存放重复的HTML代码
      <head th:fragment="commonheader">
          <meta charset="UTF-8">
          <title>公共页面</title>
      
          <link href="css/style.css" th:href="@{/css/style.css}" rel="stylesheet">
          <link href="css/style-responsive.css" th:href="@{css/style-responsive.css}" rel="stylesheet">
      
          <script src="js/html5shiv.js" th:src="@{js/html5shiv.js}"></script>
          <script src="js/respond.min.js" th:src="@{js/respond.min.js}"></script>
      </head>
      

上面代码中的head标签中的代码为公共代码其中th:fragment="commonheader"就是将head标签设为公共代码,除此之外,还可以将公共代码加一个id属性。

  • 然后是抽取公共代码
<div th:include="common :: commonheader"></div>

<div th:replace="common :: #leftmenu"></div>

上面两句代码都是获取公共代码,两个冒号之前代表的是公共HTML文件,两个冒号之后代表的是公共的标签,上面的是通过th:fragment获取的,下面的那个是通过id选择器获取的。

  • thym遍历
                <tr class="gradeX" th:each="user,stats:${users}">
                    <td th:text="${stats.count}"></td>
                    <td th:text="${user.userName}"></td>
                    <td th:text="${user.password}"></td>
                </tr>

上面的遍历是将遍历所得的内容放入表格中
${中存放的是从controller层发送过来的数组或集合}
user是单个元素
stats是状态。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值