模板引擎——Thymeleaf

本文介绍SpringBoot中Thymeleaf模板引擎的基本用法,包括表达式、字面量、文本操作、数学和布尔运算等内容,并展示了如何在实际项目中使用Thymeleaf进行页面渲染。

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

一. thymeleaf简介

  • SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染
  • Thymeleaf是用来开发Web和独立环境项目的服务器端的Java模版引擎

二. 基本语法

1.表达式

表达式名字语法用途
变量取值${…}获取请求域、session域、对象等值
选择变量*{…}获取上下文对象值
消息#{…}获取国际化等值
链接@{…}生成链接
片段表达式~{…}jsp:include作用,引用公共页面片段

2、字面量

文本值: ‘one text’ , ‘Another one!’ ,…
数字: 0 , 34 , 3.0 , 12.3 ,…
布尔值: true , false
空值: null
变量: one,two,… 变量不能有空格

3、文本操作
字符串拼接: +
变量替换: |The name is ${name}|

4、数学运算
运算符: + , - , * , / , %

5、布尔运算
运算符: and , or
一元运算: ! , not

6、比较运算
比较: > , < , >= , <= ( gt , lt , ge , le )等式: == , != ( eq , ne )

7、条件运算
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)

8、特殊操作
无操作: _

三.设置属性值-th:attr

  • 设置单个值
<form action="subscribe.html" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  </fieldset>
</form>
  • 设置多个值
<img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />

以上两个的代替写法 th:xxxx

<input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>

<form action="subscribe.html" th:action="@{/subscribe}">
  • 迭代
<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>
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">

  <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>
  • 条件运算
<a href="comments.html"

th:href="@{/product/comments(prodId=${prod.id})}"

th:if="${not #lists.isEmpty(prod.comments)}">view</a>
<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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值