thymeleaf基本应用

一、使用条件

在pom.xml中引入依赖

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

在html页面的html标签加上

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

后续代码基本是写在原有html标签的属性上。

二、使用示例

1、基本

表达式名称

语法

用途

变量取值

${}

获取请求域、session、对象等

选择变量

*{}

获取上下文对象值

消息

#{}

获取国际化等值

链接

@{}

生成链接

片段表达式

~{}

jsp:include作用,引入公共页面

<!--引入静态资源-->
<script type="text/javascript" th:src="@{/static/js/thymeleaf.js}"></script>
<!--文本-->
<span th:text="${s.id}"></span>
<!--class属性-->
<tr th:class="${status.even}?'even':'odd'" th:each="s,status:${students}">

2、循环

<tr th:class="${status.even}?'even':'odd'" th:each="s,status:${students}">
    <td th:text="${s.id}">ID</td>
    <td th:text="${s.name}">姓名</td>
</tr>

status里面包含的信息大致如下:

属性

说明

index

从0开始的索引值

count

从1开始的索引值

size

集合内元素的总量

current

当前的迭代对象

even/odd

boolean类型的,用来判断是偶数个还是奇数个

first

boolean类型,判断是否为第一个

last

boolean类型,判断是否为最后一个

3、if判断条件

<!-- 当students集合为空则显示提示信息 -->
<div th:if="${#lists.isEmpty(students)}">studnets集合为空!</div>
<!-- 当students集合不为空时才会显示下面的元素 -->
<div th:if="${not #lists.isEmpty(students)}">

th:if主要控制是否显示元素

#lists.isEmpty()语法是Thymeleaf模板自带的一种内置工具 ,可以参考SpringBoot系列教材 (三十三)- Thymeleaf - thymeleaf 内置工具用法示例和手册

4、js访问后端数据

<script th:inline="javascript">
    var single = [[${student}]];
    console.log(single.name + "/" + single.id);
</script>

5、页面包含

<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footer1">
    <p>All Rights Reserved</p>
</footer>
<footer id="footerById" th:fragment="footer2(start,now)">
    <p th:text="|${start} - ${now} All Rights Reserved|"></p>
</footer>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Thymeleaf快速入门-Hello Thymeleaf</title>
</head>
<body>
<div th:include="include::footer1"></div>
<div th:replace="include::footer2(2015,2018)"></div>
<div th:insert="include::footer1"></div>
/*
或者
<div th:include="~{include::footer1}"></div>
<div th:replace="~{include::footer2(2015,2018)}"></div>
<div th:insert="~{include::footer1"}></div>
*/
</body>
</html>

注意,<div th:replace="include::footer2(2015,2018)"></div>里面的include是上面放置公共页面元素的页面名,也就是页面名接标记名,也可以使用id,<div th:replace="include::#footerById"></div>

显示效果:

代码效果:

<!--include,div还在,插入的是footer里面的内容,3.0之后不推荐使用-->
<div>
    <p>All Rights Reserved</p>
</div>
<!--replace,div被footer替换-->
<footer>
    <p>2015 - 2018 All Rights Reserved</p>
</footer>
<!--insert,div里插入footer-->
<div>
    <footer>
        <p>All Rights Reserved</p>
    </footer>
</div>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值