Thymeleaf简介

Thymeleaf简介

Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发,模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎除了thymeleaf之外还有Velocity、FreeMarker等模板引擎,功能类似。

结合Spring Boot

  • 添加依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

  • 修改spring boot配置文件
# 开发阶段,建议关闭thymeleaf的缓存
spring.thymeleaf.cache=false
#使用遗留的html5以去掉对html标签的校验
spring.thymeleaf.mode=LEGACYHTML5

thymeleaf会对html中的标签进行严格校验,如果html标签缺少结束标签的话,thymeleaf会报错,我们可以通过下面方式去除thymeleaf的校验,添加依赖:

<dependency>
      <groupId>net.sourceforge.nekohtml</groupId>
      <artifactId>nekohtml</artifactId>
      <version>1.9.22</version>
  </dependency> 
  • 第一个thymeleaf程序

编写html页面:在resources/templates里面创建一个index.html,填写下面内容,注意添加这个xmlns:th=“http://www.thymeleaf.org”:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> 
<head>
    <meta charset="UTF-8">
    <title>thymeleaf</title>
</head>
<body>
<h1 th:text="${name}">Spring boot集成 Thymeleaf</h1>
</body>
</html>

编写controller控制器:

@Controller
public class ThymeleafCtrl {
    @GetMapping("/")
    public String hello(Model model){
        model.addAttribute("name","jack");
        return "index";
    }
}

注意:这里的return使用的默认前缀和后缀,使用thymeleaf模板,默认前缀是resources下的templates目录,后缀是html;其他情况前缀是resources下的static目录,后缀是html。maven构建工具的就是webapp,jsp了。

== Springboot使用thymeleaf作为视图展示的时候,我们将模板文件放置在resource/templates目录下,静态资源放置在resource/static目录下。==

thymeleaf表达式

  1. 标准变量表达式${},th:text用来获取controller中返回的数据。
//定义接口
@GetMapping("/thymeleaf/one")
    public String one(Model model){
        User user=new User();
        user.setUsername("zhansan");
        user.setPassword("123456");
        model.addAttribute("user",user);
        model.addAttribute("message","this is a message");
        return "one";
    }
<!--前端获取数据的的方法,通过getter,或者 Object.property -->
<p th:text="${user.getUsername()}">username</p>
<p th:text="${user.getPassword()}">password</p>
<p th:text="${user.username}">username</p>
<p th:text="${user.password}">password</p>

<!--如果这里直接接收user,就相当于toString,是一段字符串,拿不到具体数据-->

2.选择变量表达式*{},单独用和标准量一样,结合用相当于是先使用th:object将user对象取出,然后在里面的th:text中获取user对象中的属性值。

<table>
    <tr th:text="${user}">
        <td th:text="*{user.password}"></td>
        <td th:text="*{user.username}"></td>
    </tr>
</table>
  1. url表达式@{...}:将后台传入的数据拼接到url中
<!--引用绝对 URL-->
<script type="text/javascript" th:src="@{http://localhost:8080/hello.js}"></script>
	<!--等价于:-->
<script type="text/javascript" src="http://localhost:8080/hello.js"></script>

<!-----------------分割------------------>

<!--上下文相关的 URL-->
	<!--application.properties 中配置 Spring Boot 的上下文,以便于测试:
		server.servlet.context-path=/app引用路径:-->
<script type="text/javascript" th:src="@{/hello.js}"></script>
	<!--等价于:-->
<script type="text/javascript" src="/app/hello.js"></script>

<!------------------分割----------------->
<!--相对 URL-->
	<!--自动补上上下文-->
<script type="text/javascript" th:src="@{~/hello.js}"></script>

<!------------------分割------------------>

<!--带参数的 URL-->
<script type="text/javascript" th:src="@{/hello.js(name='javaboy',age=99)}"></script>
	<!--等价于:-->
<script type="text/javascript" th:src="/hello.js?name=javaboy&age=99"></script>
	<!--动态参数用标准表达式替换即可-->
  1. 国际通用表达式,通常的国际化属性:#{…} 用于获取国际化语言翻译值。即properties等文件的信息
# 在 resources 目录下新建两个文件:messages.properties
message = thymeleaf 中引用 message,系统会根据浏览器的语言环境显示不同的值:

<div th:text="#{message}"></div>
  1. 表达式的变量

文本字面量:‘one text’, ‘Another one!’,…
数字字面量:0, 34, 3.0, 12.3,…
布尔字面量:true, false
Null字面量:null
字面量标记:one, sometext, main

文本可以使用 + 进行拼接。如果字符串中包含变量,也可以使用另一种简单的方式,叫做字面量置换,用 | 代替 ‘…’ + ‘…’,如下:

<div th:text="'recived message is'+${message}"></div>
<div th:text="|recived message is ${message}|"></div>

算术运算有:+, -, *, / 和 %。

布尔运算:二元运算符:and, or布尔非(一元运算符):!, not

比较运算:表达式里的值可以使用 >, <, >= 和 <= 符号比较。==和 != 运算符用于检查相等。

​ 它们也有符号表示:gt (>);lt (<);ge (>=);le (<=);not (!)。还有 eq (==), neq/ne (!=)。

三目运算:th:text="(username eq ‘zhansan’ ) ? true : false "

  1. 内置对象
// 注意: 下面的一个#是thymeleaf的语法,多个#是注释
#ctx:上下文对象。
#vars: 上下文变量。
#locale:上下文区域设置。
#request:(仅在 Web 上下文中)HttpServletRequest 对象。
#response:(仅在 Web 上下文中)HttpServletResponse 对象。
#session:(仅在 Web 上下文中)HttpSession 对象。
#servletContext:(仅在 Web 上下文中)ServletContext 对象。

##########

###### 在页面可以访问到上面这些内置对象:
<div th:text='${#session.getAttribute("name")}'></div>
###### 和在java中用法一致,通过.调用属性或方法。
	
##########

###### 还有以下内置对象

#execInfo:有关正在处理的模板的信息。
#messages:在变量表达式中获取外部化消息的方法,与使用#{...}语法获得的方式相同。
#uris:转义URL / URI部分的方法
#conversions:执行配置的转换服务(如果有)的方法。
#dates:java.util.Date对象的方法:格式化,组件提取等
#calendars:类似于#dates但是java.util.Calendar对象。
#numbers:用于格式化数字对象的方法。
#strings:String对象的方法:contains,startsWith,prepending / appending等
#objects:一般对象的方法。
#bools:布尔评估的方法。
#arrays:数组方法。
#lists:列表的方法。
#sets:集合的方法。
#maps:地图方法。
#aggregates:在数组或集合上创建聚合的方法。
#ids:处理可能重复的id属性的方法
  1. 遍历

数组/集合/Map/Enumeration/Iterator 等的遍历也算是一个非常常见的需求,Thymeleaf 中通过 th:each 来实现遍历.

<table border="1"> 
    <tr th:each="u : ${users}"> 
        <td th:text="${u.username}"></td> <td th:text="${u.address}"></td> 
    </tr>
</table>
<!--users 是要遍历的集合/数组,u 则是集合中的单个元素。-->

遍历的时候,我们可能需要获取遍历的状态,Thymeleaf 也对此提供了支持:

index:当前的遍历索引,从0开始。
count:当前的遍历索引,从1开始。
size:被遍历变量里的元素数量。
current:每次遍历的遍历变量。
even/odd:当前的遍历是偶数次还是奇数次。
first:当前是否为首次遍历。
last:当前是否为最后一次遍历。
  1. 分支语句

条件分支使用th:if,除了布尔类型,非0数字,字符都为true,其他状态为false。

<table border="1"> 
    <tr th:each="u : ${users}" th:if="${u.status}"> 
        <td th:text="${u.username}"></td> <td th:text="${u.address}"></td> 
    </tr>
</table>

th:unlessth:if完全相反。

选择分支使用th:swithth:case联合使用。

  1. 本地变量

在thymeleaf也可以定义局部变量,使用 th:with可以定义一个本地变量.

  1. 内联文本

除了使用th:text等,在属性中接收数据外,也可以将数据内联```[[…]]``:

<div>hello [[${user.username}]]</div>

[[...]]对应于 th:text(结果会是转义的 HTML),[(...)]对应于 th:utext,它不会执行任何的 HTML 转义。

内联方式有一个问题,我们使用 Thymeleaf 的一大优势在于不用动态渲染就可以直接在浏览器中看到显示效果,当我们使用属性配置的时候确实是这样,但是如果我们使用内联的方式,各种表达式就会直接展示在静态网页中。

也可以在 js 或者 css 中使用内联th:inline="javascript":

<script th:inline="javascript"> var username=[[${user.username}]] console.log(username)</script>

  1. 引用静态资源

引用静态资源文件,CSS使用th:href,js使用使用th:src,链接URL使用th:href

  1. thymeleaf布局

通过th:fragrent定义代码片段

通过th:includeth:replace引用代码片段

  1. 常用关键字
关键字功能案例
th:id替换id<input th:id="'xxx' + ${collect.id}"/>
th:text文本替换<p th:text="${collect.description}">description</p>
th:utext支持html的文本替换<p th:utext="${htmlcontent}">conten</p>
th:object替换对象<div th:object="${session.user}">
th:value属性赋值<input th:value="${user.name}" />
th:with变量赋值运算<div th:with="isEven=${prodStat.count}%2==0"></div>
th:style设置样式th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick点击事件th:onclick="'getCollect()'"
th:each属性赋值tr th:each="user,userStat:${users}">
th:if判断条件<a th:if="${userId == collect.userId}" >
th:unless和th:if判断相反<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href链接地址<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:src图片类地址引入<img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
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">1.all:删除包含标签和所有的孩子。2.body:不包含标记删除,但删除其所有的孩子。3.tag:包含标记的删除,但不删除它的孩子。4.all-but-first:删除所有包含标签的孩子,除了第一个。5.none:什么也不做。这个值是有用的动态评估。
ction表单提交的地址<form action="subscribe.html" th:action="@{/subscribe}">
th:remove删除某个属性<tr th:remove="all">1.all:删除包含标签和所有的孩子。2.body:不包含标记删除,但删除其所有的孩子。3.tag:包含标记的删除,但不删除它的孩子。4.all-but-first:删除所有包含标签的孩子,除了第一个。5.none:什么也不做。这个值是有用的动态评估。
th:attr设置标签属性,多个属性可以用逗号分隔比如th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xvwen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值