1.Thymeleaf是什么
-
Thymeleaf是用来开发Web和独立环境项目的服务器端的Java模版引擎
-
Spring官方支持的服务的渲染模板中,并不包含jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注Thymeleaf的语法即可。
Thymeleaf 如何使用
导入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf 的配置信息我们可以通过读源码来获取:
在我们不配置的情况下 默认前缀是classpath:/templates/
也就是资源文件在templates/ 才可以被引擎读到.
当然我们也可以通过配置 他的前缀路径
spring:
thymeleaf:
prefix: classpath:/static/
比如像这样,在这里我就不配置了.
导入依赖后 编写controller层返回数据
编写index.html 并放入到摸版文件中
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<h3 th:text="${user}"></h3>
<h3 th:each="user:${users}" th:text="${user}"></h3>
<h3 th:each="user:${users}" >[[${user}]]</h3> <!-- 第二种写法-->
</body>
</html>
请求测试
这样这个小demo就完成了
2. Thymeleaf语法大全
首先 在我们引入一个项目摸版时,需要先导入HTML页面,但是css和js可能会失效所以就需要
在 herf 上添加
th:herf="@{/user/login}"
·只要是url 就需要 @{} 表达式
2.1 导航栏分离。
摸版中可能会有,相同的导航栏,造成代码冗余。
我们可以试用 th:fragment 标签来分离出来公共导航栏
比如
<nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sidebar">
当需要引用这个导航栏时
使用
th:insert 或 replace 标签
<div th:replace="~{common/common::topbar}"/>
或
<div th:insert="~{common/common::topbar}"/>
common 是路径 common/common是存放公共代码块的html页面。
topbar 是fragment 的名称
2.2 语法传参
对于导航栏以及其他 需要传递参数来保证 高亮的正确性。这时候就要用到传递参数。
Thymeleaf传参格式如下:
<div th:replace="~{common/common::sidebar(active='list.html')}"/>
根据所传递参数来实现具体逻辑:
<a th:class="${active=='list.html'? 'nav-link active':'nav-link'}" th:href="@{/emp/showlist(active='list.html')}">