Thymeleaf笔记

Thymeleaf 介绍

简单说,Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:

  • 1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 Thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
  • 2.Thymeleaf 开箱即用的特性。它提供标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL表达式效果,避免每天套模板、该 Jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  • 3.Thymeleaf 提供 Spring 标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

标准表达式语法

它们分为四类:

  • 1.变量表达式
  • 2.选择或星号表达式
  • 3.文字国际化表达式
  • 4.URL 表达式

变量表达式

变量表达式即 OGNL 表达式或 Spring EL 表达式(在 Spring 术语中也叫 model attributes)。如下所示:

${session.user.name}

它们将以HTML标签的一个属性来表示:

<span th:text="${book.author.name}">
<li th:each="book : ${books}">

文字国际化表达式

文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties),用 Key 索引 Value,还可以提供一组参数(可选).

#{main.title}  
#{message.entrycreated(${entryId})}  

可以在模板文件中找到这样的表达式代码:

<table>
 ...  
<th th:text=" #{header.address.city}">...</th>
<th th:text = "#{header.address.country}">...</th>
 ...  
</table>

URL 表达式

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

@{/order/list}

URL还可以设置参数:

@{/order/details(id=${orderId})}

相对路径:

@{../documents/report}

让我们看这些表达式:

<form th:action = "@{/createOrder}">
<a href = "main.html" th:href= "@{/main}">

表达式支持的语法

字面(Literals)
  • 文本文字(Text literals): 'one text','Another one!',…
  • 数字文本(Number literals): 0,34,3.0,12.3,…
  • 布尔文本(Boolean literals): true,false
  • 空(Null literal): null
  • 文字标记(Literal tokens): one,sometext,main,…
文本操作(Text operations)
  • 字符串连接(String concatenation): +
  • 文本替换(Literal substitutions): |Thenameis${name}|
算术运算(Arithmetic operations)
  • 二元运算符(Binary operators): +,-,*,/,%
  • 减号(单目运算符)Minus sign (unary operator): -
布尔操作(Boolean operations)
  • 二元运算符(Binary operators): and,or
  • 布尔否定(一元运算符)Boolean negation (unary operator): !,not
比较和等价(Comparisons and equality)
  • 比较(Comparators): >,<,>=,<=(gt,lt,ge,le)
  • 等值运算符(Equality operators): ==,!=(eq,ne)
条件运算符(Conditional operators)
  • If-then: (if)?(then)
  • If-then-else: (if)?(then):(else)
  • Default: (value) ?: (defaultvalue)

几种常用的使用方法

1、赋值、字符串拼接
<span th:text= "|Welcome to our application, ${user.name}!|">

2、条件判断 If/Unless

Thymeleaf中使用th:if和th:unless属性进行条件判断,下面的例子中, <a>标签只有在 th:if中条件成立时才显示

<a th:if = "${myself=='yes'}"></i></a>
<a th:unless =${session.user != null} th:href ="@{/login}">Login</a>

th:unless 于 th:if 恰好相反,只有表达式中的条件不成立,才会显示其内容。
也可以使用 (if)?(then):(else)这种语法来判断显示的内容

3、for 循环
<tr th:each="collect,iterStat : ${collects}">
  <th scope= "row" th:text= "${collect.id}">1</th>
  <td>  <img th:src ="${collect.webLogo}"/></td>
  <td th:text= "${collect.url}">Mark</td>
  <td th:text="${collect.title}">Otto</td>
  <td th:text="${collect.description}">@mdo</td>
  <td th:text="${terStat.index}">index</td>
</tr>

iterStat称作状态变量,属性有:

  • index:当前迭代对象的 index(从0开始计算)
  • count: 当前迭代对象的 index(从1开始计算)
  • size:被迭代对象的大小
  • current:当前迭代变量
  • even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
  • first:布尔值,当前循环是否是第一个
  • last:布尔值,当前循环是否是最后一个

配置与使用

1.在application.properties文件中增加Thymeleaf模板的配置。

#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

说明一下,这些配置不是必须的,如果配置了会覆盖默认的。
在开发时建议将spring.thymeleaf.cache设置为false,否则会有缓存,导致页面没法及时看到更新后的效果。
比如你修改了一个文件,已经update到tomcat,但刷新页面还是之前的页面,就是因为缓存引起的。

2.在pom.xml中添加thymeleaf的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3.编写一个测试的Controller

@RequestMapping(value = "/greeting")
public ModelAndView test(ModelAndView mv) {
    mv.setViewName("/greeting");
    mv.addObject("title","欢迎使用Thymeleaf!");
    return mv;
}

可以看到,Controller与普通的SpringMVC的Controller无异。

4.编写greeting.html

spring-boot项目静态文件目录:/src/java/resources/static
spring-boot项目模板文件目录:/src/java/resources/templates
所以greeting.html文件在/src/java/resources/templates下。

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link th:href="@{/css/1.css}" rel="stylesheet"/>
</head>
<body>
<p th:text="'Hello, ' + ${title}" /><br/>

<script th:src="@{/js/jquery/1.11.0/jquery.js}"></script>
<script>
    $(function(){
       alert("page load finish.");
    });
</script>
</body>
</html>

5.运行效果

运行样式.jpg

这里这是一个基本的使用示例,更多Thymeleaf的用法请自行搜索。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容