-
SpringBoot 的Thrmeleaf模板引擎
Spring Boot中推荐使用Thrmeleaf作为模板引擎,因为Thrmeleaf 提供了完美的SpringMVC的支持
。虽然Spring Boot 中还提供了其他的大量的模板,包括:Free Marker,Groovy,Velocity和Mustache -
Thrmeleaf 是一个Java类库,可以作为
MVC的Web应用的View层
。 -
Thrmeleaf 还提供了额外的模块与SpringMVC集成,所以我们可以使用
Thrmeleaf 完全替代JSP
。 -
下面的代码是一个基本的Thrmeleaf 模板页面:
<!DOCTYPE html>
<html xmlns:th="http://www.thrmeleaf.org"><!-- 可以将静态页面转换成动态的视图,需要进行动态处理的元素将使用"th:"为前缀 -->
<head>
<meta charset="UTF-8">
<title>默认页面</title>
</head>
<body>
</body>
</html>
- 访问model中的数据
<div>
<div>
<h3>访问model</h3>
</div>
<div>
<!-- 访问model中的singlePerson 的name属性,注意:需要处理的动态内容需要加上"th:"前缀 -->
<span th:text="${singlePerson.name}"></span>
</div>
</div>
- model中的数据迭代:
<div>
<div>
<h3>列表</h3>
</div>
<div>
<ul>
<!-- 使用 th:each来做循环迭代,person作为迭代元素来使用,然后像访问model中的数据那一步一样来访问迭代元素的属性-->
<li class="list-group-item" th:each="person:${people}">
<span th:text="person.name"></span>
<span th:text="person.age"></span>
</li>
</ul>
</div>
</div>
7.数据判断
<!-- 判断people是否为空,Thrmeleaf支持>、<、>=、<=、==、 !=作为比较条件,同时也支持将SpringEl表达式语言用于条件中 -->
<div th:if="${not #list.isEmpty(people)}">
<div>
<div>
<h3>列表</h3>
</div>
<div>
<ul>
<!-- 使用 th:each来做循环迭代,person作为迭代元素来使用,然后像访问model中的数据那一步一样来访问迭代元素的属性-->
<li class="list-group-item" th:each="person:${people}">
<span th:text="person.name"></span>
<span th:text="person.age"></span>
</li>
</ul>
</div>
</div>
</div>
8.在JavaScript中访问model
<script th:inline="javascript">
var single = [${singlePerson}];
console.log(single.name + "/" + single.age);
</script>