Thymeleaf基本使用

Thymeleaf简介

Spring官方支持的服务的渲染模板中,并不包含jsp。但是支持一些模板引擎技术,目前官方比较流行的有:Thymeleaf,Freemarker,Mustache…

Thymeleaf官方网站:https://www.thymeleaf.org/index.html
在这里插入图片描述

Thymeleaf是用来开发Web和独立环境项目的现代服务器端Java模板引擎,既适用于 web 环境,也适用于独立环境,比较适合当前的人员分工问题。其能够处理HTML、XML、JavaScript、CSS 甚至纯文本。提供了一种优雅且高度可维护的模板创建方法,可以直接在浏览器中正确显示,也可以作为静态原型方便开发团队协作。

Thymeleaf特点:

  • 动静结合: Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。
    Thymeleaf支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
  • 开箱即用: Thymeleaf提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  • 多方言支持: Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
  • 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。

环境准备

使用Spring Initializr快速创建一个工程:
在这里插入图片描述
在这里插入图片描述

勾选web和Thymeleaf的依赖:
在这里插入图片描述

项目结构:

在这里插入图片描述

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ly</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>thymeleaf</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致我们修改页面不会立即被展现,因此我们关闭缓存。

# 关闭Thymeleaf的缓存
spring:
  thymeleaf:
    cache:
      false

另外,修改完毕页面,需要使用快捷键:Ctrl + Shift + F9来刷新工程。
在这里插入图片描述

快速入门

我们准备一个controller,控制视图跳转:

@Controller
public class HelloController {

    @GetMapping("hello")
    public String show1(Model model){
        model.addAttribute("msg", "Hello, Thymeleaf!");
        return "index";
    }
}

新建一个html模板:

语法说明:

Thymeleaf通过${}来获取model中的变量,注意这不是el表达式,而是ognl表达式,但是语法非常像。不过区别在于,我们的表达式写在一个名为:th:text的标签属性中,这个叫做指令

<!DOCTYPE html>
<!--把html 的名称空间,改成:xmlns:th="http://www.thymeleaf.org" 会有语法提示-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
	<h1 th:text="${msg}">大家好</h1>
</body>
</html>

启动项目,访问页面:

在这里插入图片描述
动静结合:

Thymeleaf崇尚自然模板,意思就是模板是纯正的html代码,脱离模板引擎,在纯静态环境也可以直接运行。现在如果我们直接在html中编写 ${}这样的表达式,显然在静态环境下就会出错,这不符合Thymeleaf的理念。

Thymeleaf中所有的表达式都需要写在指令中,指令是HTML5中的自定义属性,在Thymeleaf中所有指令都是以th:开头。因为表达式${user.name}是写在自定义属性中,因此在静态环境下,表达式的内容会被当做是普通字符串,浏览器会自动忽略这些指令,这样就不会报错了!

th常用标签

标签作用样例
th:id替换id<input th:id="${user.id}"/>
th:text文本替换<p text:="${user.name}">name</p>
th:utext支持html的文本替换<p utext:="${htmlcontent}">content</p>
th:object替换对象<div th:object="${user}"></div>
th:value属性赋值<input th:value="${user.name}" >
th:with变量赋值运算<div th:with="isEven=${user.age}%2==0"></div>
th:style设置样式th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:src替换资源<script type="text/javascript" th:src="@{index.js}"></script>
th:onclick点击事件th:onclick="'getCollect()'"
th:href替换超链接<a th:href="@{index.html}">url</a>
th:each迭代<tr th:each="student:${user}" >
th:if判断条件<a th:if="${userId == collect.userId}" >
th:unless和th:if判断相反<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:switch多路选择,配合th:case 使用<div th:switch="${user.role}">
th:caseth:switch的一个分支<p th:case="'admin'">User is an administrator</p>
th:fragment布局标签,定义一个代码片段,方便其它地方引用<div th:fragment="alert">
th:include布局标签,替换内容到引入的文件<head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace布局标签,替换整个标签到引入的文件<div th:replace="fragments/header :: title"></div>
th:selectedselected选择框 选中th:selected="(${xxx.id} == ${configObj.dd})"
th:inline定义js脚本可以使用变量<script type="text/javascript" th:inline="javascript">
th:action表单提交的地址<form action="subscribe.html" th:action="@{/subscribe}">
th:remove删除某个属性<tr th:remove="all"> all:删除所有的孩子、body:删除其所有的孩子,不包含标签、tag:删除标签、all-but-first:删除除第一个以外的所有、none:什么也不做

变量

新建一个实体类:User

public class User {
    
    private String name;
    private int age;
	private boolean sex;
    private String role;
    //Get、Set
}

然后在模型中添加数据

@GetMapping("add")
public String addUser(Model model){
    User user = new User();
    user.setAge(21);
    user.setName("<font color='red'>小明</font>");
    
    model.addAttribute("user", user);
    return "user";
}

th:text指令出于安全考虑,会把表达式读取到的值进行处理,防止html的注入。例如,<p>你好</p>将会被格式化输出为$lt;p$gt;你好$lt;/p$lt;如果想要不进行格式化输出,而是要输出原始内容,则使用th:utext来代替.

示例:我们在页面获取user数据:

<h1>
    欢迎您:<span th:utext="${user.name}">---</span>
</h1>

效果:
在这里插入图片描述

ognl表达式的语法糖:

刚才获取变量值,我们使用的是经典的对象.属性名方式。但有些情况下,我们的属性名可能本身也是变量,怎么办?ognl提供了类似js的语法方式:

例如:${user.name} 可以写作${user['name']}

自定义变量

看下面的案例:

<h2>
    <p>Name: <span th:text="${user.name}">Jack</span>.</p>
    <p>Age: <span th:text="${user.age}">21</span>.</p>
</h2>

我们获取用户的所有信息,分别展示。当数据量比较多的时候,频繁的写user.就会非常麻烦。因此,Thymeleaf提供了自定义变量来解决:

<h2 th:object="${user}">
    <p>Name: <span th:text="*{name}">Jack</span>.</p>
    <p>Age: <span th:text="*{age}">21</span>.</p>
</h2>
  • 首先在 h2上 用 th:object="${user}"获取user的值,并且保存
  • 然后,在h2内部的任意元素上,可以通过 *{属性名}的方式,来获取user中的属性,这样就省去了大量的user.前缀了

方法调用

ognl表达式本身就支持方法调用,例如:

<h2 th:object="${user}">
    <p>FirstName: <span th:text="*{name.split(' ')[0]}">first</span>.</p>
    <p>LastName: <span th:text="*{name.split(' ')[1]}">last</span>.</p>
</h2>

这里我们调用了name(是一个字符串)的split方法。

Thymeleaf内置对象

Thymeleaf中提供了一些内置对象,并且在这些对象中提供了一些方法,方便我们来调用。获取这些对象,需要使用#对象名来引用。

环境相关对象:

对象作用
#ctx获取Thymeleaf自己的Context对象
#requset如果是web程序,可以获取HttpServletRequest对象
#response如果是web程序,可以获取HttpServletReponse对象
#session如果是web程序,可以获取HttpSession对象
#servletContext如果是web程序,可以获取HttpServletContext对象

Thymeleaf提供的全局对象:

对象作用
#dates处理java.util.date的工具对象
#calendars处理java.util.calendar的工具对象
#numbers用来对数字格式化的方法
#strings用来处理字符串的方法
#bools用来判断布尔值的方法
#arrays用来护理数组的方法
#lists用来处理List集合的方法
#sets用来处理set集合的方法
#maps用来处理map集合的方法
  • 举例

我们在环境变量中添加日期类型对象

@GetMapping("date")
public String date(Model model){
    model.addAttribute("today", new Date());
    return "date";
}

在页面中处理

<p>
    今天是: <span th:text="${#dates.format(today,'yyyy-MM-dd')}">2020-03-30</span>
</p>

效果:
在这里插入图片描述

字面值

有的时候,我们需要在指令中填写基本类型如:字符串、数值、布尔等,并不希望被Thymeleaf解析为变量,这个时候称为字面值。

字符串字面值:

使用一对'引用的内容就是字符串字面值了:

<h1 th:text="'${msg}'">大家好</h1>

th:text中的${msg}并不会被认为是变量,而是一个字符串:

在这里插入图片描述

数字字面值:

数字不需要任何特殊语法, 写的什么就是什么,而且可以直接进行算术运算

<p>今年是 <span th:text="2021">1999</span>.</p>
<p>两年后将会是 <span th:text="2021 + 2">2001</span>.</p>

在这里插入图片描述

布尔字面值:

布尔类型的字面值是true或false:

<div th:if="true">
    你填的是true
</div>

这里引用了一个th:if指令,跟vue中的v-if类似

拼接

我们经常会用到普通字符串与表达式拼接的情况:

<span th:text="'欢迎您:' + ${user.name} + '!'"></span>

字符串字面值需要用'',拼接起来非常麻烦,Thymeleaf对此进行了简化,使用一对|即可:

<span th:utext="|欢迎您:${user.name}!|"></span>

与上面是完全等效的,这样就省去了字符串字面值的书写。

在这里插入图片描述

运算

需要注意:${}内部的是通过OGNL表达式引擎解析的,外部的才是通过Thymeleaf的引擎解析,因此运算符尽量放在${}外进行,例如: <span th:text="${user.age}+2"></span>

算术运算:

支持的算术运算符:+ - * / %

比较运算:

支持的比较运算:>, <, >= , <= ,但是>, <不能直接使用,因为xml会解析为标签,要使用别名。

注意 == and !=不仅可以比较数值,类似于equals的功能。

可以使用的别名:gt (>), lt (<), ge (>=), le (<=), not (!). Also eq (==), neq/ne (!=).

三元运算:

<span th:text="${user.sex} ? '':''"></span>

三元运算符的三个部分:conditon ? then : else

  • condition:条件
  • then:条件成立的结果
  • else:不成立的结果

其中的每一个部分都可以是Thymeleaf中的任意表达式。有的时候,我们取一个值可能为空,这个时候需要做非空判断,可以使用 表达式 ?: 默认值简写: <span th:text="${user.name} ?: '小红' "></span>,当前面的表达式值为null时,就会使用后面的默认值。 注意:?:之间没有空格。

循环

循环也是非常频繁使用的需求,我们使用th:each指令来完成:

假如有用户的集合:users在Context中。

<tr th:each="user : ${users}"> 
    <td th:text="${user.name}">name</td>
    <td th:text="${user.age}">age</td>
</tr>
  • ${users} 是要遍历的集合,可以是以下类型:
    • Iterable,实现了Iterable接口的类
    • Enumeration,枚举
    • Interator,迭代器
    • Map,遍历得到的是Map.Entry
    • Array,数组及其它一切符合数组结果的对象

在迭代的同时,我们也可以获取迭代的状态对象:

<tr th:each="user,stat : ${users}">
    <td th:text="${user.name}">name</td>
    <td th:text="${user.age}">age</td>
</tr>

stat对象包含以下属性:

  • index,从0开始的角标
  • count,元素的个数,从1开始
  • size,总元素个数
  • current,当前遍历到的元素
  • even/odd,返回是否为奇偶,boolean值
  • first/last,返回是否为第一或最后,boolean值

逻辑判断

Thymeleaf中使用th:if 或者 th:unless ,两者的意思恰好相反。

<span th:if="${user.age} < 24">小鲜肉</span>

如果表达式的值为true,则标签会渲染到页面,否则不进行渲染。

以下情况被认定为true:

  • 表达式值为true
  • 表达式值为非0数值
  • 表达式值为非0字符
  • 表达式值为字符串,但不是"false","no","off"
  • 表达式不是布尔、字符串、数字、字符中的任何一种

其它情况包括null都被认定为false

分支控制switch

这里要使用两个指令:th:switchth:case

<div th:switch="${user.role}">
  <p th:case="'admin'">用户是管理员</p>
  <p th:case="'manager'">用户是经理</p>
  <p th:case="*">用户是别的玩意</p>
</div>

需要注意的是,一旦有一个th:case成立,其它的则不再判断。与java中的switch是一样的。

另外th:case="*"表示默认,放最后。

URL表达式

URL表达式指的是把一个有用的上下文或回话信息添加到URL,这个过程经常被叫做URL重写:@{/user}

URL还可以设置参数: @{/user/find(id=${userId})}
相对路径: @{../aaa/bbb}

案例:引入css样式

在static目录下新建一个app.css文件
在这里插入图片描述
设置样式:

.app{
    height: 200px;
    width: 200px;
    background-color: darkblue;
}

代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
    <link rel="stylesheet" th:href="@{app.css}">
</head>
<body>

    <div class="app"></div>


</body>
</html>

运行结果:
在这里插入图片描述

JS模板

模板引擎不仅可以渲染html,也可以对JS中的进行预处理。而且为了在纯静态环境下可以运行,其Thymeleaf代码可以被注释起来:

<script th:inline="javascript">
    const user = /*[[${user}]]*/ {};
    const age = /*[[${user.age}]]*/ 20;
    console.log(user);
    console.log(age)
</script>

内联文本:[[...]]内联文本的表示方式, 在script标签中通过th:inline="javascript"来声明这是要特殊处理的js脚本,th:inline可以在父级标签内使用,甚至作为body的标签。

语法结构:

const user = /*[[Thymeleaf表达式]]*/ "静态环境下的默认值";

因为Thymeleaf被注释起来,因此即便是静态环境下, js代码也不会报错,而是采用表达式后面跟着的默认值。

看看页面的源码:

在这里插入图片描述

我们的User对象被直接处理为json格式了,非常方便。

控制台:

在这里插入图片描述

通过th:fragment提取公共的代码

方式一:

抽取一个公共片段: th:frament="片段名"

引入公共片段的方式有三种:

  • th:insert:将公共片段整个替换到标签中
  • th:replace:公共片段直接对标签以及标签内部的内容进行替换
  • th:include:公共片段(不包括自己的主标签)对标签内容进行替换

在页面中引用: ~{模板名 :: 片段名}

方式二:

在要提取的公共片段上添加能够唯一标识该标签的id或css等属性,之后通过 {模板名 :: 选择器} 的方式引用。

样例

需要抽取的公共片段component.html,我们可以将多个需要抽取的片段写在一个文件里面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<div th:fragment="com1">
    111
</div>

<div th:fragment="com2">
    222
</div>

<div id="com3">
    333
</div>

</html>

在页面中使用:

<!DOCTYPE html>
<!--把html 的名称空间,改成:`xmlns:th="http://www.thymeleaf.org"` 会有语法提示-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
    <link rel="stylesheet" th:href="@{app.css}">
</head>
<body>

    <div th:replace="~{component::com1}"></div>

	<!--保留原来的标签-->
    <div th:insert="~{component::com2}"></div>

	<!--只需要在公共组件添加一个 id 或 class 等只要css 能唯一定位到的属性即可   (此处以 id 为例)-->
    <div th:insert="~{component::#com3}"></div>

 
</body>
</html>

结果:
在这里插入图片描述

注意:在调用fragment时是从Thymeleaf文件的根路径:src/main/resource/templates开始的,如果像读取子路径下的代码块应该配置相应的路径。

给组件传递参数:

定义:

<div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>

使用:

<div th:include="::frag (${value1},${value2})">...</div>

<div th:include="::frag (onevar=${value1},twovar=${value2})">...</div> 
等价于 
<div th:include="::frag" th:with="onevar=${value1},twovar=${value2}">

案例:实现导航栏

新建一个模板布局 _framents.html :

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:fragment="head(title)">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:replace="${title}">模板布局</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
</head>
<body>

<!--导航-->
<nav th:fragment="menu(n)" class="ui m-bg attached segment animated fadeInDown" style="z-index: 999!important;">
    <div class="ui container">
        <!--stackable:可堆叠,屏幕小的时候会堆叠到一块,用于适应移动端网页适配-->
        <div class="ui secondary stackable menu">
            <!--teal颜色header-->
            <h2 class="ui teal header item">导航栏</h2>
            <!--home icon:图标-->
            <a th:href="@{/page1}" class="teal m-item item" th:classappend="${n==1} ? 'active'"></i>第一页</a>
            <a th:href="@{/page2}" class="teal m-item item" th:classappend="${n==2} ? 'active'"></i>第二页</a>
            <a th:href="@{/page3}" class="teal m-item item" th:classappend="${n==3} ? 'active'"></i>第三页</a>

            <!--right:靠右-->
            <div class="right item m-mobile-hide">
                <!--可以加transparent:透明-->
                <div class="ui icon input ">
                    <input type="text" placeholder="Search....">
                    <i class="search link icon"></i>
                </div>
            </div>
        </div>

    </div>
</nav>

    </br>
    </br>
    </br>
    </br>

</body>
</html>

新建三个页面:page1.html、page2.html、page3.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="_fragments :: head(~{::title})">
    <meta charset="UTF-8">
    <title>第二页</title>
    <link rel="stylesheet">
</head>
<body>

<nav th:replace="_fragments :: menu(2)" class="ui inverted attached segment"></nav>
<h1>第二页</h1>

</body>
</html>

运行结果:

在这里插入图片描述

  • 37
    点赞
  • 99
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙源lll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值