springboot:Java模板引擎Thymeleaf介绍
Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。
Thymeleaf初探
相比于其他的模板引擎,Thymeleaf最大的特点是通过HTML的标签属性渲染标签内容,以下是一个Thymeleaf模板例子:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Good Thymes Virtual Grocery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
</head>
<body>
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
</body>
</html>
这是一段标准的HTML代码,这也就意味着通过浏览器直接打开它是可以正确解析它的结构并看到页面的样子。相比去其他的模板引擎在指定的位置通过${}
等表达式进行渲染,Thymeleaf则是一种针对HTML/XML定制的模板语言(当然它可以被扩展),它通过标签中的th:text
属性来填充该标签的一段内容。上例中,<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
意味着<p>
标签中的内容会被表达式#{home.welcome}
的值所替代,无论模板中它的内容是什么,之所以在模板中“多此一举“地填充它的内容,完全是为了它能够作为原型在浏览器中直接显示出来。
标准表达式语法
变量
Thymeleaf模板引擎在进行模板渲染时,还会附带一个Context存放进行模板渲染的变量,在模板中定义的表达式本质上就是从Context中获取对应的变量的值:
<p>Today is: <span th:text="${today}">13 february 2011</span>.</p>
假设today
的值为2015年8月14日
,那么渲染结果为:<p>Today is: 2015年8月14日.</p>
。可见Thymeleaf的基本变量和JSP一样,都使用${.}
表示获取变量的值。
URL
URL在Web应用模板中占据着十分重要的地位,需要特别注意的是Thymeleaf对于URL的处理是通过语法@{...}
来处理的。Thymeleaf支持绝对路径URL:
<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>
同时也能够支持相对路径URL:
- 当前页面相对路径URL——
user/login.html
,通常不推荐这样写。 - Context相关URL——
/static/css/style.css
另外,如果需要Thymeleaf对URL进行渲染,那么务必使用th:href
,th:src
等属性,下面是一个例子
<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html"
th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
几点说明:
- 上例中URL最后的(orderId=${o.id})表示将括号内的内容作为URL参数处理,该语法避免使用字符串拼接,大大提高了可读性
@{...}
表达式中可以通过{orderId}
访问Context中的orderId
变量@{/order}
是Context相关的相对路径,在渲染时会自动添加上当前Web应用的Context名字,假设context名字为app,那么结果应该是/app/order
字符串替换
很多时候可能我们只需要对一大段文字中的某一处地方进行替换,可以通过字符串拼接操作完成:
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
一种更简洁的方式是:
<span th:text="|Welcome to our application, ${user.name}!|">
当然这种形式限制比较多,|...|
中只能包含变量表达式${...}
,不能包含其他常量、条件表达式等。
运算符
在表达式中可以使用各类算术运算符,例如+, -, *, /, %
th:with="isEven=(${prodStat.count} % 2 == 0)"
逻辑运算符>
, <
, <=
,>=
,==
,!=
都可以使用,唯一需要注意的是使用<
,>
时需要用它的HTML转义符:
th:if="${prodStat.count} > 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
循环
渲染列表数据是一种非常常见的场景,例如现在有n条记录需要渲染成一个表格<table>
,该数据集合必须是可以遍历的,使用th:each
标签:
<body>
<h1>Product list</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>
<p>
<a href="../home.html" th:href="@{/}">Return to home</a>
</p>
</body>
可以看到,需要在被循环渲染的元素(这里是<tr>
)中加入th:each
标签,其中th:each="prod : ${prods}"
意味着对集合变量prods
进行遍历,循环变量是prod
在循环体中可以通过表达式访问。
条件求值
If/Unless
Thymeleaf中使用th:if
和th:unless
属性进行条件判断,下面的例子中,<a>
标签只有在th:if
中条件成立时才显示:
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:unless
于th:if
恰好相反,只有表达式中的条件不成立,才会显示其内容。
Switch
Thymeleaf同样支持多路选择Switch结构:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
</div>
默认属性default可以用*
表示:
<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>
Utilities
为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#
直接访问:
#dates
#calendars
#numbers
#strings
arrays
lists
sets
maps
- ...
下面用一段代码来举例一些常用的方法:
#dates
/*
* Format date with the specified pattern
* Also works with arrays, lists or sets
*/
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}
/*
* Create a date (java.util.Date) object for the current date and time
*/
${#dates.createNow()}
/*
* Create a date (java.util.Date) object for the current date (time set to 00:00)
*/
${#dates.createToday()}
#strings
/*
* Check whether a String is empty (or null). Performs a trim() operation before check
* Also works with arrays, lists or sets
*/
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}
/*
* Check whether a String starts or ends with a fragment
* Also works with arrays, lists or sets
*/
${#strings.startsWith(name,'Don')} // also array*, list* and set*
${#strings.endsWith(name,endingFragment)} // also array*, list* and set*
/*
* Compute length
* Also works with arrays, lists or sets
*/
${#strings.length(str)}
/*
* Null-safe comparison and concatenation
*/
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}
/*
* Random
*/
${#strings.randomAlphanumeric(count)}
页面即原型
在Web开发过程中一个绕不开的话题就是前端工程师与后端工程师的协作,在传统Java Web开发过程中,前端工程师和后端工程师一样,也需要安装一套完整的开发环境,然后各类Java IDE中修改模板、静态资源文件,启动/重启/重新加载应用服务器,刷新页面查看最终效果。
但实际上前端工程师的职责更多应该关注于页面本身而非后端,使用JSP,Velocity等传统的Java模板引擎很难做到这一点,因为它们必须在应用服务器中渲染完成后才能在浏览器中看到结果,而Thymeleaf从根本上颠覆了这一过程,通过属性进行模板渲染不会引入任何新的浏览器不能识别的标签,例如JSP中的<form:input>
,不会在Tag内部写表达式。整个页面直接作为HTML文件用浏览器打开,几乎就可以看到最终的效果,这大大解放了前端工程师的生产力,它们的最终交付物就是纯的HTML/CSS/JavaScript文件。
springboot:Java模板引擎Thymeleaf介绍的更多相关文章
- 新一代Java模板引擎Thymeleaf
新一代Java模板引擎Thymeleaf-spring,thymeleaf,springboot,java 相关文章-天码营 https://www.tianmaying.com/tutorial/u ...
- SpringBoot:模板引擎 thymeleaf、ContentNegotiatingViewResolver、格式化转换器
目录 模板引擎 thymeleaf ContentNegotiatingViewResolver 格式化转换器 模板引擎 thymeleaf.ContentNegotiatingViewResolve ...
- SpringBoot入门:新一代Java模板引擎Thymeleaf(理论)
Spring Boot 提供了spring-boot-starter-web来为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及SpringMVC的 ...
- Spring MVC : Java模板引擎 Thymeleaf (二)
本文原计划直接介绍Thymeleaf的视图解析,但考虑到学习的方便,决定先构建一个spring-mvc. 以下的全部过程仅仅要一个记事本和JDK就够了. 第一步,使用maven构建一个web app. ...
- SpringBoot入门:新一代Java模板引擎Thymeleaf(实践)
菜鸟教程:http://www.runoob.com/ http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js http://apps.b ...
- Spring MVC : Java模板引擎 Thymeleaf (三)
以下以构造一个表单開始,解说 Thymeleaf的使用方法. 为了演示方便,还是以经典的注冊为例. 这是Thymeleaf的form的形式, <form action="#" ...
- 转--Spring MVC : Java模板引擎 Thymeleaf (三)
原文:http://www.csdn.com/html/topnews201408/49/1349.htm 下面以构造一个表单开始,讲解 Thymeleaf的用法.为了演示方便,还是以经典的注册为例. ...
- Java模板引擎FreeMarker介绍和使用
http://blog.csdn.net/shimiso/article/details/8778793
- SpringBoot入门系列(四)整合模板引擎Thymeleaf
前面介绍了Spring Boot的优点,然后介绍了如何快速创建Spring Boot 项目.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/ ...
随机推荐
- 如何解决XMLHttpRequest cannot load file:~~~~~~~~~~~. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-res
原因:Chrome不支持本地Ajax请求. 解决: 右击Chrome浏览器快捷方式,选择“属性”,在“目标”中加上"--allow-file-access-from-files", ...
- 《Linux就该这么学》今天开课了-Linux的发展,起源
秦时明月当中的经典语录:失败的人只有一种,就是在抵达成功之前放弃的人——盖聂 想到这里我只想说,决定一件事,就要坚持,或许结局并不美好,但过程值得回忆
- CSS Grid
效果图如上所示 <!DOCTYPE html> <html> <head> <title>练习</title> </head> ...
- ELK学习
[root@log-node1 ~]# cobbler repo add --name=logstash-2.3 --mirror=http://packages.elastic.co/logstas ...
- js-闪烁的文字
<!DOCTYPE html><html> <head lang="en"> <meta charset=" ...
- Django View 进阶
返回404 from django.http import HttpResponse, HttpResponseNotFound def not_found(request): ) 或 return ...
- Socket通信的Demo
https://blog.csdn.net/shankezh/article/details/70763579
- cad.net 利用win32api实现不重复打开dwg路径的文件夹(资源管理器)
这里地址的方法也是可用的,但是net3.5不能使用 为此我选择使用win32api的方式来遍历当前桌面所有资源管理器 /// <summary> /// 不重复打开dwg路径的资源管理器 ...
- 如何正确的使用Ubuntu以及安装常用的渗透工具集.
文章来源i春秋 入坑Ubuntu半年多了 记得一开始学的时候基本一星期重装三四次=-= 尴尬了 觉得自己差不多可以的时候 就吧Windows10干掉了 c盘装Ubuntu 专心学习. 这里主要来 ...
- mybatis 控制台打印sql语句
其实很简单,打印SQL只需要加一个setting就可以了.亲测可用. mybatis-config.xml: <settings> <setting name=&quo ...