3.3.2 Thymeleaf功能简介
在HTML页面上使用Thymeleaf标签语言,用一个简单的关键字“th”来标注。使用Thymeleaf标签语言的典型例子如下:
<h3 th:text="${actor.name}"></h3>
<img th:src="@{/images/logo.png}"/>
其中,th:text指定了在标签<h3>中显示的文本,它的值来自于关键字“$”所引用的内存变量,th:src设定了标签<img>的图片文件的链接地址,既可以是绝对路径,也可以是相对路径。下面列出了Thymeleaf的一些主要标签和函数。
th:text,显示文本。
th:utext:和th:text的区别是针对"unescaped text"。
th:attr:设置标签属性。
th:if or th:unless:条件判断语句。
th:switch,th:case:选择语句。
th:each:循环语句。
#dates:日期函数。
#calendars:日历函数。
#numbers:数字函数。
#strings:字符串函数。
#objects:对象函数。
#bools:逻辑函数。
#arrays:数组函数。
#lists:列表函数。
本章的实例工程将在视图设计中使用Thymeleaf的下列几个主要功能,而有关Thymeleaf的详细说明和介绍可以访问它的官方网站http://www.thymeleaf.org/,以获得更多的帮助。
1.?使用功能函数
Thymeleaf有一些日期功能函数、字符串函数、数组函数、列表函数等,代码清单3-11是Thymeleaf使用日期函数的一个例子,#dates.format是一个日期格式化的使用实例,它将电影的创建日期格式化为中文环境的使用格式“'yyyy-MM-dd HH:mm:ss'”。
代码清单3-11 Thymeleaf使用函数
th:value="${movie.createDate} ? ${#dates.format(movie.createDate,'yyyy-MM-dd HH:mm:ss')} :''"
2.?使用编程语句
Thymeleaf有条件语句、选择语句、循环语句等。代码清单3-12使用each循环语句来显示一个数据列表,即在下拉列表框中使用循环语句来显示所有的演员列表。
代码清单3-12 th:each循环
<select name="actorid" id="actorid">
<option value="">选择演员</option>
<option th:each="actor:${actors}"
th:value="${actor.id}"
th:text="${actor.name}">
</option>
</select>
3.?使用页面框架模板
Thymeleaf的页面框架模板是比较优秀的功能。预先定义一个layout,它具有页眉、页脚、提示栏、导航栏和内容显示等区域,如代码清单3-13所示。其中,layout:fragment=
" prompt"是一个提示栏,它可以让引用的视图替换显示的内容;fragments/nav :: nav是一个导航栏并指定了视图文件,也就是说它不能被引用的视图替换内容;layout:fragment="content"是一个主要内容显示区域,它也能由引用的视图替换显示内容;fragments/footer :: footer是一个页脚定义并且也指定了视图文件,即不被引用的视图替换显示内容。这样设计出来的页面模板框架如图3-1所示。
代码清单3-13 layout模板
<div class="headerBox">
<div class="topBox">
<div class="topLogo f-left">
<a href="#"><img th:src="@{/images/logo.png}"/></a>
</div>
<div class="new-nav">
<h3>电影频道</h3>
</div>
</div>
</div>
<div class="locationLine" layout:fragment=" prompt ">
当前位置:首页 > <em>页面</em>
</div>
<table class="globalMainBox" style="position:relative;z-index:1">
<tr>
<td class="columnLeftBox" valign="top">
<div th:replace="fragments/nav :: nav"></div>
</td>
<td class="whiteSpace"></td>
<td class="rightColumnBox" valign="top">
<div layout:fragment="content"></div>
</td>
</tr>
</table>
<div class="footBox" th:replace="fragments/footer :: footer"></div>
图3-1 页面框架模板
有了页面模板之后,就可以在一个主页面视图上引用上面的layout,并替换它的提示栏prompt和主要内容显示区域content,其他页眉、页脚和导航栏却保持同样的内容,如代码清单3-14所示。这样就可以设计出一个使用共用模板的具有统一风格特征的界面。
代码清单3-14 使用layout模板的视图设计
<html xmlns:th="http://www.thymeleaf.org" layout:decorator="fragments/layout">
……
<div class="locationLine" layout:fragment=" prompt ">
当前位置:首页 > <em >电影管理</em>
</div>
<div class="statisticBox w-782" layout:fragment="content">
......
</div>