以下一切均基于《Spring Boot 实战》一书
Thymeleaf是一个Java类库,它是一个xml/xhtml/html5的模板引擎,可以作为MVC的Web应用的view层。
Thymeleaf还提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全替代JSP。
下面将列举几种常用的用法
1.引入Thymeleaf
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8">
<link th:src="@{bootstrap/css/bootstrap.min.css}" ref="stylesheet"/>
<link th:src="@{bootstrap/css/bootstrap-theme.min.css}" ref="stylesheet"/>
<body>
<script th:src="@{jquery-1.10.2.min.js}"type="text/javascript" />
<script th:src="@{bootstrap/js/bootstrap.min.js}" />
</body>
</head>
通过xmlns:th=”http://www.thymeleaf.org”命名空间,将镜头页面转换为动态的视图。需要进行动态处理的元素将使用 th 为前缀
通过“”@{}“”引用web资源
2.访问model中的属性
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">访问model</h3>
</div>
<div class="panel-body">
<span th:text="${singlePerson.name}" />
</div>
</div>
使用访问model中singlePerson的name属性,动态内容需要添加th
3.model中的数据迭代
Thymeleaf的迭代和JSP的写法也很相似,代码如下:
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">列表</h3>
</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item" th:each="person:${people}">
<span th:text="${person.name}" />
<span th:text="${person.age}" />
</li>
</ul>
</div>
</div>
使用th:each=”person:${people}”来进行迭代,person作为迭代元素来使用
4.数据判断
<div th:if="${not #lists.isEmpty(people)}">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">列表</h3>
</div>
<div class="panel-body">
<li class="list-group-item" th:each="person:${people}">
<span th:text="${person.name}" />
<span th:text="${person.age}" />
</li>
</div>
</div>
</div>
通过th:if=”${not #lists.isEmpty(people)}”表达式判断people是否为空