Springboot 之 引入Thymeleaf

本文详细介绍了在SpringBoot框架中使用Thymeleaf模板引擎的方法,包括依赖添加、基本语法、变量获取、URL引入、字符串替换、运算符使用、条件判断、循环等关键特性。

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

一.介绍

开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。SpringBoot支持如下页面模板语言

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • JSP

二.添加依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Spring Boot默认存放模板页面的路径在src/main/resources/templates或者src/main/view/templates,这个无论是使用什么模板语言都一样,当然默认路径是可以自定义的,不过一般不推荐这样做。另外Thymeleaf默认的页面文件后缀是.html。

三.基本语法

首先要在改写html标签

<html xmlns:th="http://www.thymeleaf.org">

这样的话才可以在其他标签里面使用th:*这样的语法.这是下面语法的前提.

1).获取变量值
<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>

获取变量值用$符号,$表达式只能写在th标签内部,不然不会生效,上面例子就是使用th:text标签的值替换p标签里面的值.

2).引入URL

Thymeleaf对于URL的处理是通过语法@{…}来处理的

<a th:href="@{http://blog.youkuaiyun.com/u012706811}">绝对路径</a>
<a th:href="@{/}">相对路径</a>
<a th:href="@{css/bootstrap.min.css}">Content路径,默认访问static下的css文件夹</a>

类似的标签有:th:hrefth:src

3).字符串替换

通过字符串拼接操作完成:

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
4).运算符

在表达式中可以使用各类算术运算符,例如+, -, *, /, %

<p th:with="isEven=(${prodStat.count} % 2 == 0)"></p>
5).条件
  • if / unless
    Thymeleaf中使用th:if和th:unless属性进行条件判断,下面的例子中,标签只有在th:if中条件成立时才显示:
<a th:if="${myself=='yes'}" > </i> </a>
<a th:unless=${session.user != null} th:href="@{/login}" >Login</a>

th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。

  • Switch
 <div th:switch="${user.role}">
 <p th:case="'admin'">User is an administrator</p>
 <p th:case="#{roles.manager}">User is a manager</p>
 </div>

默认属性default可以用*表示:

<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
6).循环
  <table>
    <tr>
      <th>NAME</th>
      <th>PRICE</th>
      <th>IN STOCK</th>
    </tr>
    <tr th:each="prod : ${prods}">
      <td th:text="${prod.name}">Onions</td>
      <td th:text="${prod.price}">2.41</td>
      <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    </tr>
  </table>
  <p>
    <a href="../home.html" th:href="@{/}">Return to home</a>
  </p>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值