【Thymeleaf】Thymeleaf 学习笔记
目录
一、Thymeleaf 介绍
1.1 Thymeleaf 概念
1.2 Thyeleaf 特点
二、Thymeleaf 使用
2.1 基本语法
2.1.1 输出文本内容 th:text
2.1.2 表单提交 th:action
2.1.3 for循环 th:each
2.1.4 Map 输出
2.1.5 时间输出
2.1.6 条件判断
2.1.7 定义模块
2.1.8 图片识别
2.1.9 url 跳转
一、Thymeleaf 介绍
1.1 Thymeleaf 概念
thymeleaf 是一个模板引擎工具,主要用于页面渲染操作(页面数据填充操作),可以取代之前的 jsp 操作。
thymeleaf 是一个XML/XHTML/HTML5模板引擎,可以用于 Web 与非 Web 环境中的应用开发。在应用开发中,你可以使用 thymeleaf 来完全代替 JSP 或其他的模板引擎,如 Velocity、FreeMarker等。
thymeleaf 的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也称为静态建模,你可以使用它创建经过验证的 XML/HTML 模板,开发者只需将标签属性添加到模板中即可,这些设定好的标签属性会在 DOM 上执行预先制定好的逻辑。
1.2 Thyeleaf 特点
开箱即用,支持处理六种模板:
二、Thymeleaf 使用
2.1 基本语法
2.1.1 输出文本内容 th:text
java:
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "hello thymeleaf");
return "demo1";
}
html:
<div th:text="${message}"></div>
<!-- 能够识别到html标签并显示 -->
<div th:utext="${message}"></div>
2.1.2 表单提交 th:action
<form id="login-form" th:action="@{/test/hello}">
<button>提交</button>
</form>
2.1.3 for循环 th:each
<table>
<tr>
<th>下标</th>
<th>ID</th>
<th>姓名</th>
<th>地址</th>
</tr>
<!--
第一个参数 user: 当前被循环的对象 item
第二个参数 state: 当前被循环对象的状态记录,如下标、第几条
-->
<tr th:each="user,state:${users}">
<td th:text="${state.count}"></td>
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.address}"></td>
</tr>
</table>
2.1.4 Map 输出
--------------------- .java ------------------
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("num", "105");
dataMap.put("name", "小王");
dataMap.put("address", "深圳");
model.addAttribute("dataMap", dataMap);
--------------------- .html ------------------
<div>
<!--
读取map的种方式
1. 知道 map 的key,根据 key 直接获取数据
2. 不知道 key,使用循环方式获取key,然后获取数据
-->
<h1>方式一</h1>
<div>获取num的值:<span th:text="${dataMap.num}"></span></div>
<div>获取name的值:<span th:text="${dataMap.name}"></span></div>
<div>获取address的值:<span th:text="${dataMap.address}"></span></div>
<h1>方式二</h1>
<div th:each="item:${dataMap}">
<div><span th:text="${item.key}"></span><span th:text="${item.value}"></span></div>
</div>
</div>
2.1.5 时间输出
<span th:text="${#dates.format(now, 'yyyy-MM-dd HH:mm:ss')}"></span>
2.1.6 条件判断
下面这两句话是等同的
# 当条件成立 th:if
<span th:if="${age>18}">成年人</span>
# 当条件不成立 th:unless
<span th:unless="${age>18}">成年人</span>
2.1.7 定义模块
th: fragment 用于定义一个独立的模块,可以被其他页面引用
定义一个 footer.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>子模块</title>
</head>
<body>
<!-- 定义一个模块 -->
<div th:fragment="bar">
关于我们<br/>
</div>
</body>
</html>
在展示页面中使用 th:include=”[文件名称]::[片段名称]“引用
<div th:include="footer::bar"></div>
2.1.8 图片识别
<img th:src="${item.image}" />
2.1.9 url 跳转
url表达式有其特殊的格式:
@{}
如下面实现点击跳转:
使用 @{}表明这是修改url ${url}可以获取到当前url 括号中可以是扩充的内容
<a th:href="@{${url}(category=${category})}" th:text="${category}"></a><em th:unless="${state.last}">、</em>
还没有评论,来说两句吧...