thymeleaf入门使用

springboot默认不支持JSP,所以需要引入第三方模板引擎技术实现页面渲染
整合thymeleaf需要引入starter依赖

<!--引入thymeleaf依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency

所有的thymeleaf页面都是html后缀,并且应该放在templates目录下,而且在html标签中加入名称空间

xmlns:th="http://www.thymeleaf.org"

所有的标签在thymeleaf中都用其对应的th:的前缀写法

基本使用

在jsp中,使用request作用域中的变量我们使用${}的形式来使用,在thymeleaf中也是同样的方式

<h1 th:text="${msg}"></h1>

thymeleaf中可以使用@{}的形式引用链接

<!--改变一个属性的值 使用 th:href 使用$符号获取的是link对应的value-->
<a href="www.baidu.com" th:href="${link}">去百度</a>
<!--使用@符号相当于是内部的内容直接就是一个地址字符串,之后会直接把这个字符串拼接上去-->
<a href="www.baidu.com" th:href="@{link}">去百度</a>

当我们在application.properties配置文件中使用server.servlet.context-path属性给项目设置地址之后,使用@符号取地址,thymeleaf就会自动给地址前加上项目的地址,但是必须是绝对路径的写法(以/开头的地址写法),相对路径就是不以斜杠开头

静态导入

我们可以将页面的公共部分进行抽取,在common页面中存放公共的部分,语法为

<!--name就是名称-->
<div th:fragment="name">
	公共部分
</div>

在使用的时候有语法供我们选择 th:insert th:replace th:include
语法

<div th:insert="~{footer :: copy}"></div>
或者
<div th:insert="footer :: copy"></div>

三者的区别

<body>

  ...
  <div th:insert="footer :: copy"></div>  将公共部分连同标签一同导入
  <div th:include="footer :: copy"></div> 将公共部分的标签内部的内容导入
  <div th:replace="footer :: copy"></div> 将原来的标签直接替换为公共部分的标签
  
</body>

对应的结果

<body>

  ...
  <div>
      <footer>
    	&copy; 2011 The Good Thymes Virtual Grocery
  	  </footer>
  </div>
  <div>
    &copy; 2011 The Good Thymes Virtual Grocery
  </div>
  <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
  </footer>
</body>

循环

语法

<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>

在循环变量的后面加上一个status就可以使用thymeleaf中自带的一些变量,例如count表示计数,从1开始

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值