Spring boot(五)模板引擎 Thymeleaf

Thymeleaf 是一款用于渲染 XML/XHTML/HTML 5 内容的模板引擎。类似 JSP、Velocity、FreeMaker 等,它也可以轻易的与 Spring MVC 等 Web 框架进行集成作为 Web 应用的模板引擎。与其他模板引擎相比,Thymeleaf 最大的特点是能够直接在浏览 器中打开并正确显示模板页面,而不需要启动整个 Web 应用。

pom配置

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

在 application.properties 中添加配置:

spring.thymeleaf.cache=false

前端html页面标签中引入如下:

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

常用语法:

1.赋值、字符串拼接:

<p th:text="${userName}">neo</p> 
<span th:text="'Welcome to our application, ' + ${userName} + '!'"></span>

字符串拼接还有另外⼀种简洁的写法:

<span th:text="|Welcome to our application, ${userName}!|"></span>

2.条件判断 If/Unless

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

<a th:if="${flag == 'yes'}"  th:href="@{/home}"> home </a> 
<a th:unless="${flag != 'no'}" th:href="@{http://www.baidu.com/}" >baidu</a>

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

3.for 循环

<table> 
   <tr th:each="user,iterStat : ${users}"> <td th:text="${user.name}">neo</td> 
      <td th:text="${user.age}">6</td> 
      <td th:text="${user.pass}">213</td> 
      <td th:text="${iterStat.index}">index</td> 
</tr> </table>

iterStat 称作状态变量,属性有:
index:当前迭代对象的 index(从 0 开始计算)
count:当前迭代对象的 index(从 1 开始计算)
size:被迭代对象的⼤⼩
current:当前迭代变量
even/odd:布尔值,当前循环是否是偶数/奇数(从 0 开始计算)

first:布尔值,当前循环是否是第一个

last:布尔值,当前循环是否是最后一个

4.URL

URL 在 Web 应用模板中占据着十分重要的地位,需要特别注意的是 Thymeleaf 对于 URL 的处理是通过语法 @{...} 来处理的。

如果需要 Thymeleaf 对 URL 进行渲染,那么务必使用 th:href、th:src 等属性,下面举一个例子:

<a th:href="@{http://www.ityouknow.com/{type}(type=${type})}">link1</a> 
<a href="details.html" th:href="@{http://www.ityouknow.com/{pageId}/can-use-springcloud.html(page Id=${pageId})}">view</a>
<a th:href="@{/list}" class="btn btn-info">Back</a>

设置背景:map.addAttribute("img", "http://www.ityouknow.com/assets/images/neo.jpg");

<div th:style="'background:url(' + @{${img}} + ');'">

5.内联 [ [ ] ]

内联文本:[[...]] 内联文本的表示方式,使用时,必须先用在 th:inline="text/javascript/none" 激活,th:inline 可以在父级标签内使用,甚至作为 body 的标签。内联文本尽管比⽐ th:text 的代码少,不利于原型显示。

文本内联:

<div th:inline="text" > 
    <h1>内联js</h1> 
    <p>Hello, [[${userName}]]</p> 
    <br/> 
</div>

脚本内联,脚本内联可以在 js 中取到后台传过来的参数:

<script th:inline="javascript"> 
    var name = [[${userName}]] + ', Sebastian'; 
    alert(name); 
</script>

6.内嵌变量

为了模板更加易用,Thymeleaf 还提供了一系列 Utility 对象(内置于 Context 中),可以通过 # 直接访问:

dates:java.util.Date 的功能方法类
calendars: 类似 #dates,面向 java.util.Calendar
numbers:格式化数字的功能方法类
strings:字符串对象的功能类,contains、startWiths、prepending/appending 等
objects:对 objects 的功能类操作
bools: 对布尔值求值的功能方法
arrays:对数组的功能类方法
lists:对 lists 的功能类方法
sets
maps
...


下面用一段代码来举例一些常用的方法:

dates
<p th:text="${#dates.format(date, 'dd/MMM/yyyy HH:mm')}">neo</p> 
<p th:text="${#dates.createToday()}">neo</p> <p th:text="${#dates.createNow()}">neo</p>
strings
<p th:text="${#strings.isEmpty(userName)}">userName</p> 
<p th:text="${#strings.listIsEmpty(users)}">userName</p> 
<p th:text="${#strings.length(userName)}">userName</p> 
<p th:text="${#strings.concat(userName)}"></p> 
<p th:text="${#strings.randomAlphanumeric(count)}">userName</p>

html5的操作支持:

th:abbr          th:accept             th:accept-charset
th:accesskey             th:action             th:align
th:alt             th:archive             th:audio
th:autocomplete             th:axis             th:background
th:bgcolor             th:border             th:cellpadding
th:cellspacing             th:challenge             th:charset
th:cite             th:class             th:classid
th:codebase             th:codetype             th:cols
th:colspan             th:compact             th:content
th:contenteditable             th:contextmenu             th:data
th:datetime             th:dir             th:draggable
th:dropzone             th:enctype             th:for
th:form             th:formaction             th:formenctype
th:formmethod             th:formtarget             th:fragment
th:frame             th:frameborder             th:headers
th:height             th:high             th:href
th:hreflang             th:hspace             th:http-equiv

th:icon             th:id             th:inline
th:keytype             th:kind             th:label
th:lang             th:list             th:longdesc
th:low             th:manifest             th:marginheight
th:marginwidth             th:max             th:maxlength
th:media             th:method             th:min
th:name            th:onabort            th:onafterprint
th:onbeforeprint            th:onbeforeunload            th:onblur
th:oncanplay            th:oncanplaythrough            th:onchange
th:onclick            th:oncontextmenu            th:ondblclick
th:ondrag            th:ondragend            th:ondragenter
th:ondragleave            th:ondragover            th:ondragstart
th:ondrop            th:ondurationchange            th:onemptied
th:onended            th:onerror            th:onfocus
th:onformchange            th:onforminput            th:onhashchange
th:oninput            th:oninvalid            th:onkeydown
th:onkeypress            th:onkeyup            th:onload
th:onloadeddata            th:onloadedmetadata            th:onloadstart
th:onmessage            th:onmousedown            th:onmousemove
th:onmouseout            th:onmouseover            th:onmouseup
th:onmousewheel            th:onoffline            th:ononline
th:onpause            th:onplay            th:onplaying
th:onpopstate            th:onprogress            th:onratechange
th:onreadystatechange            th:onredo            th:onreset
th:onresize            th:onscroll            th:onseeked
th:onseeking            th:onselect            th:onshow
th:onstalled            th:onstorage            th:onsubmit
th:onsuspend            th:ontimeupdate            th:onundo
th:onunload            th:onvolumechange            th:onwaiting
th:optimum            th:pattern            th:placeholder
th:poster            th:preload            th:radiogroup
th:rel            th:rev            th:rows
th:rowspan            th:rules            th:sandbox
th:scheme            th:scope            th:scrolling
th:size            th:sizes            th:span
th:spellcheck            th:src            th:srclang
th:standby            th:start            th:step
th:style            th:summary            th:tabindex
th:target            th:title            th:type
th:usemap            th:value            th:valuetype
th:vspace            th:width            th:wrap

th:vspace            th:width            th:wrap
th:xmlbase            th:xmllang            th:xmlspace

7.所有可用值表达式: *{…}

比如*{name} 从可用值中查找name,如果有上下文,比如上层是object,则查object中的name属性。

8.操作模板

布局是最常用的功能之一,不论是前端还是后台都避免不了,使用Thymeleaf 布局非常简单,下面来演示一下: 首先定义一个代码片段 copyright.html,放到 layout 目录下:

<footer th:fragment="copyright"> 
&copy; 2017 
</footer>

创建 index.html 在⻚⾯任何地⽅引⼊:

<body> 
    <div th:include="layout/copyright :: copyright"></div> 
</body>

layout 是文件夹地址,fileName 是文件名,语法这样写:layout/fileName:htmlhead 。
htmlhead 是指定义的代码⽚段 如 th:fragment="htmlhead"。

原文地址:https://www.cnblogs.com/person008/p/9578843.html