【springboot & thymeleaf】thymeleaf 快速入门(精讲)

CodingDict上的使用文档:https://codingdict.com/article/28305

一、什么是thymeleaf

Thymeleaf是一个现代服务器端Java模板引擎,适用于Web和独立环境,能够处理HTML,XML,JavaScript,CSS甚至纯文本。

在jsp阶段,我们是通过jsp写前端页面,虽然有JSTL和EL表达式,但是并内有做的前后端分写,而且写起来比较笨重。因此出现了"模版引擎",因为模版引擎的出现,使得我们可以直接通过html页面编写前端页面,将极大地方便了开发。


Thymeleaf可以处理六种模板

  • HTML
  • XML
  • TEXT
  • JAVASCRIPT
  • CSS
  • RAW



二、使用前的准备工作

导入相关依赖(pom.xml)

<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
	<groupId>org.thymeleaf.extras</groupId>
	<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

通过thymeleaf渲染的html页面必须存放在\项目\src\main\resources\templates下面。

引入头文件

对于使用thymeleaf的html,需要引入头文件xmlns:th="http://www.thymeleaf.org",例如:

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



三、基本语法

1、标准表达式语法

①、简单表达式

${}:变量表达式。是获取容器上下文变量的值,应该是包括所有上下文中的key-value(存放在attribute中的键值对)。


@{}:超链接url表达式。@{}这个是thymeleaf中的链接,@{/hom}的效果和http://localhost:8080/hom是一样的。我们有时也会面临传递参数的问题,thymeleaf给我们提供了解决方法,@{/home(id='1',value='寒江')}的效果和http://localhost:8080/hom?id='1'&value='寒江'是一样的。


*{}:选择表达式。选择表达式与变量表达式有一个重要的区别:选择表达式捕捉的是选定的对象的上下文,而不是整个上下文。如下:

<div th:object="${person}">
    <p th:text="*{name}"></p>
    <p th:text="*{age}"></p>
    <p th:text="*{gender}"></p>
</div>

#{}:资源表达式。用于获取配置文件中的信息(常用于国际化),如:

新建/resources/test01.properties

user.name=寒江
user.age=18
user.gender=

新建/resources/templates/test.html

<p th:text="#{user.name}">This text will not be show! </p>
<p th:text="#{user.age}">This text will not be show! </p>
<p th:text="#{user.gender}">This text will not be show! </p>

#maps:工具对象表达式,这些工具对象就像是java对象,可以访问对应java对象的方法来进行各种操作。如下:

<div th:if="${#maps.isEmpty(msg)}"></div>

[[…]]:文本内联,这个我就个例子你就明白了

<div>你好,我是[[${username}]]</div>

②、算术运算

+ , - , * , / , % :二元运算符

- : 负号(一元运算符)

③、布尔操作

and,or: 二元操作符

!,not: 非(一元操作符)


④、关系操作符

> , < , >= , <= :大于、小于、大于等于、小于等于

== , !=  :等于、不等于


2、使用文本

对于使用模版引擎实现前后端的数据的交互,我们首先需要解决的是怎么从服务器端获取传递过来的文本

接收服务器传传递的文本的接收方式有两种

①、转译纯文本

对于服务器端传递过来的HTML代码,会将其转换成HTML代码,在浏览器上显示渲染后的信息

<div th:utext="#{...}"></div>

例如:

@RequestMapping("/test")
public String test(Model model){
    model.addAttribute("msg","<div>hello thymeleaf!<div>");
    return "test";
}
<div th:utext="${msg}"></div>

在这里插入图片描述


②、非转译纯文本

对于服务器端传递过来的HTML代码,不会将其转换成HTML代码,直接显示文本内容

<div th:text="#{...}"></div>

例如:

@RequestMapping("/test")
public String test(Model model){
    model.addAttribute("msg","<div>hello thymeleaf!<div>");
    return "test";
}
<div th:text="${msg}"></div>

在这里插入图片描述

3、设置属性值

在HTML中 通常标签上都会有属性值,如下:actiontypevalue

<form action="subscribe.html">
  <fieldset>
    <div value="massage"></div>
    <input type="submit" value="Subscribe!" />
  </fieldset>
</form>
<img src="../../images/gtvglogo.png"/>
<a href="http://localhost:8080/gohome">返回首页</a>

当我们使用thymeleaf后,thymeleaf给我们提供了一全套的属性值的设置方法。

<form th:action="@{/goHome}">
    <fieldset>
        <div th:value="${msg}"></div>
        <input type="submit" th:attr="value=${msg}"/>
    </fieldset>
</form>
<img th:src="@{/images/gtvglogo.png}" />
<a th:href="@{/gohome}">返回首页</a>

总结:只要是HTML中存在的属性都可以通过th:属性名="..."的形式进行替换。


4、迭代

①、foreach
   ArrayList<Person> users = new ArrayList();
   users.add(new Person("寒江1号",18));
   users.add(new Person("寒江2号",19));
   users.add(new Person("寒江3号",20));
   model.addAttribute("users",users);
<ul th:each="user : ${users}">
    <li th:text="${user.getName()}"></li>
    <li th:text="${user.getAge()}"></li>
</ul>

   int [] nums = {1, 2, 3};
   model.addAttribute("arr",nums);
<p th:each="num : ${arr}" th:text="${num}"></p>

5、条件判断

①、if、unless、(if)?(then):(else)

if:和java中的if相同,if表达式中为真这成立

<td th:if="${test.Score} > 0 and ${test.Score} < 60">不及格</td>

unless:if表达式中为假这成立

<td th:unless="${test.Score} > 0 and ${test.Score} < 60">及格</td>

(if)?(then):(else) :这个是我们最常使用的行内判断

<div th:text="${user.age==1?'':''}"></div>

<div th:class="${style==index?'weight highLight':'weight '}"></div>
②、switch-case
<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

6、表达式工具类

转载自:小虎Tiger(博客园)【点击查看】


四、模版布局

我们知道vue是实现了组件化编程的前端框架,组件化编程的好处:实现代码复用,利于项目维护。在thymeleaf模板引擎中也提供了"组件化编程"的思想——模版布局。


基本句法

介绍三个新的thymeleaf的行内标记

th:fragment=“modelname”:将某一块代码提取为模版,并且命名为modelname.

th:insert="~{path/filename:: modelname}":使用某一模版插入到某个HTML标签中。filename表示文件名,modelname表示模板名。

th:replace="~{path/filename :: modelname}":使用某一模版替换某个HTML标签。filename表示文件名,modelname表示模板名。

举例说明:

建立model.html文件并编写模版

<footer th:fragment="footer">
  <p>datetime: 2020-10-21</p>
  <p>@host:studious tiger</p>
</footer>

使用模板(假设model.html是templates目录的直接子文件)

<body>

  ...
  <!-- 插入到div中-->
  <div th:insert="~{model:: footer}"></div>
-----------------------------------------
  <!-- 替换div-->
  <div th:replace="~{model:: footer}"></div>

</body>
<body>

  ...
  <!-- 插入到div中-->
<div>
	<footer th:fragment="footer">
		<p>datetime: 2020-10-21</p>
		<p>@host:studious tiger</p>
	</footer>
</div>
-----------------------------------------
  <!-- 替换div-->
<footer th:fragment="footer">
  <p>datetime: 2020-10-21</p>
  <p>@host:studious tiger</p>
</footer>

</body>

对不同的页面中的相同的组件,我们就可以通过th:fragment="modelname"将其提取到一个新的文件中,然后在原本的文件中使用th:insert="~{path/filename:: modelname}"th:replace="~{path/filename:: modelname}"复用提取出的组件,实现代码复用和统一管理。


传递参数

对于相同的组件,因为其在不同的页面中被使用,所以难免显示会存在差异。例如:不同页面中使用的导航栏,导航栏中的高亮不同。

我们可以通过th:replace="~{path/filename:: modelname(active='nav01')}"的形式给模版传递参数。

<body>
<header th:fragment="footer">
  <div th:class="${active=='nav01'?'strong heighLight':'strong '}">Navigation-01</div>
  <div th:class="${active=='nav02'?'strong heighLight':'strong '}">Navigation-02</div>
  <div th:class="${active=='nav03'?'strong heighLight':'strong '}">Navigation-03</div>
  <div th:class="${active=='nav04'?'strong heighLight':'strong '}">Navigation-04</div>
</header >
...
</body>

这样我们就可以通过引用端的传值控制模板的样式了。


未完待续,尽请期待...

莫等闲,白了少年头,空悲切…
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值