Thymeleaf标准语法

本文详细介绍了Thymeleaf模板引擎中的各种表达式用法,包括变量、选择、消息、链接和片段表达式。并通过实例展示了如何在HTML中使用这些表达式进行数据绑定、循环迭代、URL构建和模板拼接。

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

Thymeleaf标准表达式

 

变量表达式:${}

选择表达式:*{}

消息表达式:#{}

链接表达式:@{}

片段表达式:~{}

 

变量表达式

 

获取返回的字段:

获取book对象的author字段对象的name字段值

<span th:text = "${book.author.name}"></span>

循环迭代:

books是一个collection,从中依次获取对象遍历。

<li th:each="book : ${books}"></li>

 

选择表达式

 

在指定的model中获取字段:

获取book对象的title字段

获取book对象的author字段

<div th:object="${book}">
    <span th:text="*{title}"></span>
    <span th:text="*{author}"></span>
</div>

使用th:object可以指定所选的模型,使用*{property}确定为某个字段。

 

消息表达式

 

消息表达式可以获取.properties文件中的配置信息。

<table>
    <th th:text="#{header.address.city}"></th>
    <th th:text="#{header.address.country}"></th>
</table>

 

链接表达式

 

可以简化链接的生成难度。

<a th:href="@{/order/list}"></a>

如果项目部署在myapp下,那么上述标记等价于:

<a href="/myapp/order/list">...</a>

 

通过链接表达式可以实现cookie没有打开的时候的session维护:

<a href="/myapp/order/list;jsessionid=23fa31abd41ea093">...</a>

 

实现url的带参数的创建:

<a th:href="@{/order/details(id=${orderId},type=${orderType})}">...</a>

等价于:

<a href="/myapp/order/details?id=23&amp;type=online">...</a>

也可以使用相对地址:

<a th:href="@{../documents/report}">...</a>
<a th:href="@{~/contents/main}">...</a>

 

片段表达式

 

可以使用片段表达式插入,替换,引入其他的模板

<div th:insert="~{commons :: main}">...</div>
<div th:with="frag=~{footer :: #main/text()}">
  <p th:insert="${frag}">
</div>

 

字面及操作

 

文本:'one', 'Another one'

数字:0, 34, 3.0, 12.3

布尔:true, false

空:null

字面标记:one, sometext, main

 

文本操作符:

连接:+

混合:| The name is ${name} |

 

数学运算符:

四则:+,-,*,/,%

负号:-

 

布尔运算:

二进制操作:and or

否定:!,not

 

关系运算:

比较:>,>=,<,<=

等价比较:==,!=

 

条件操作:

if-then: (if)? (then)

if-then-else: (if)?(then):(else)

default: (value)?:(defaultValue)

 

表达式预处理

 

使用__可以实现预处理:

#{selection.__${sel.code}__}

优先处理sel.code

 

常见的标记

 

1. 使用th:text替换内容

<p th:text="#{msg.welcome}">Welcome everyone!</p>

2. 使用th:each循环遍历

<li th:each="book : ${books}" th:text="${book.title}">En las Orillas del Sar</li>

3. 使用标记辅助确定其值

<form th:action="@{/createOrder}">
<input type="button" th:value="#{form.submit}" />
<a th:href="@{/admin/users}">

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值