SpringBoot使用Thymeleaf入门介绍

1. Thymeleaf简单介绍

Thymeleaf 与JSP类似,最大的区别在于,JSP在运行之后才能得纯HTML,而 Thymeleaf 在运行之前也是纯html。Thymeleaf跟 Velocity、FreeMarker 等模板引擎大同小异 ,相较与其他的模板引擎,它有如下三个极吸引人的特点:

1.Thymeleaf 在有网络和无网络的环境下皆可运行。它可以让在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

2.Thymeleaf 开箱即用。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

3.Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

举一个简单的Thymeleaf 例子:

  <body>
    <p th:text="#{hello.world}">Hello World!</p>
  </body>

这是一段标准的HTML代码,通过浏览器直接打开它是可以正确解析并且看到页面的静态效果,显示的内容是</P>标签里的文本Hello World!。标签中的th:text属性用来填充该标签的内容,也就是说在上面的例子中</P>标签中的Hello World!将会被th:text属性中#{hello.world}的值替换。假如#{hello.world}的值是Hello Thymeleaf!那么网页打开时显示的内容将会变成Hello Thymeleaf!
在传统的JSP中,我们需要在</P>标签中加入${hello.world}才能让浏览器显示数据,每次开发前端页面我们必须部署项目启动服务器之后才能显示数据,从而根据显示的数据进行美化或者修改前端的页面。使用Thymeleaf 模板引擎之后,不需要部署项目,只要在前端设置模板数据用于查看显示效果就可以了,在标签中加入th:text属性之后,项目部署时前端设置的模板数据就会被后端的数据(通常是数据库中的数据)替换,这样开发的时候就可以专注于前端或者专注于后端,大大提高我们的开发效率,如今的是趋势前后端开发分离,使用Thymeleaf 模板引擎能减少团队之间因前后端开发差异产生的问题。

2. Thymeleaf的标准表达式语法

Thymeleaf有四种标准表达式语法

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

在这里着重介绍前面两种

2.1 变量表达式

变量表达式即OGNL表达式或Spring EL表达式(在Spring术语中也叫model attributes)。像这种:${user.name}

<p>UserName is :  <span th:text="${user.name}">xiaoming</span> !</p>

默认运行结果是:UserName is : xiaoming ! 如果${user.name}的值是xiaohong则输出UserName is : xiaohong !
这种与JSP的方式一样

2.2 URL表达式

Thymeleaf对于URL的处理是通过语法@{…}来处理,举个简单的例子:

<a th:href="@{http://www.baidu.com}">Thymeleaf</a>

Thymeleaf支持绝对路径URL也支持相对路径的URL:
相对路径写法:
@{…/thymeleaf/hello(userName=${user.username})}

添加参数:

@{/thymeleaf/hello(userName=${user.username},userPassWord=${user.userpassword})}

URL后面的(userName=${user.username},userPassWord=${user.userpassword})表示将括号内的内容作为参数处理,多个参数用逗号隔开,该语法避免使用字符串拼接,大大提高了可读性

如果要对URL进行修改,可以使用 th:hrefth:src

<!-- 访问的地址是 'http://localhost:8080/thymeleaf/hello?userName=xiaoming)'  -->
<a href="hello.html" 
   th:href="@{http://localhost:8080/thymeleaf/hello(userName=${user.username})}">view</a>

<a href="hello.html" th:href="@{/thymeleaf/hello(userName=${user.username})}">view</a>

3.表达式支持的语法

3.1 算术运算

表达式支持算数运算,比如:+、-(减号)、*、/、%以及单独的 -(负号)
简单举两个例子

语法实例运行结果
+<p th:text="${Product.price+999}" ></p>1000(设Product.price为1)
-<p th:text="${Product.price-999}" ></p>1(设Product.price为1000)

3.2 逻辑运算

逻辑运算符>, <, <=,>=,==,!=,!都可以使用,唯一需要注意的是使用<,>时需要用它的HTML转义符

3.3 条件运算

If-then: (if) ? (then)

If-then-else: (if) ? (then) : (else)

Default: (value) ?: (defaultvalue)

3.4 文本操作

设${name}的值是123

操作结果
<p th:text="'Hello! ' + ${name} + '!'" >hello world</p>Hello ! 123 !
<p th:text="|Hello! ${name}!|" >hello world</p>Hello ! 123 !

4.使用方法

4.1 赋值、字符串拼接

赋值用th:text=""属性,字符串拼接参考上面3.4,运用“+”拼接或者直接用“||”都可以做到,推荐使用后者。

<p th:text="'Hello! ' + ${name} + '!'" >hello world</p>

<p th:text="|Hello! ${name}!|" >hello world</p>

设${name}的值是123,上面的输出结果都是Hello ! 123 !

4.2 条件判断If/Unless

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

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

th:unlessth:if恰好相反,只有表达式中的条件不成立,才会显示其内容

<a th:href="@{/login}" th:unless="${session.user == null}">Login</a>

也可以使用 (if) ? (then) : (else) 这种语法来判断显示的内容,如:

<p th:text="(${hello}!=null) ? '条件成立显示这个':'条件不成立显示这个'" >Hello </p>

4.3 循环遍历

  1. 直接遍历
    列表数据是一种非常常见的场景,例如现在有n条记录需要渲染成一个表格<table>,该数据集合必须是可以遍历的,使用th:each标签:
    <table>
        <thead>
        <tr>
            <th>id</th>
            <th>产品名称</th>
            <th>价格</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="p: ${ps}">
            <td th:text="${p.id}">1</td>
            <td th:text="${p.name}">name</td>
            <td th:text="${p.price}">price</td>
        </tr>
        </tbody>
    </table>

注:${ps}为一个可遍历的集合
2. 带状态遍历
还可以进行带状态的遍历,只需把遍历条件改成th:each="p,status: ${ps},status称作状态变量,属性有:

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

比如我需要在遍历的时候输出序号,可以把上面的遍历代码改成:

<tr th:each="p,status: ${ps}">
    <td th:text="${status.count}"></td>
    <td th:text="${p.id}"1></td>
    <td th:text="${p.name}">name</td>
    <td th:text="${p.price}">price</td>
</tr>

这样在每次遍历的时候都会在前面加上一个序号
3. 遍历select

    <select size="3">
        <option th:each="p:${ps}" th:value="${p.id}" th:selected="${p.id==p.id}" th:text="${p.name}" ></option>
    </select>

先在select中声明需要显示的数量size为多少
th:each="p:${ps}"是遍历的集合
th:value="${p.id}"令每一项的值是${p.id}
th:selected="${p.id==p.id}" 表示被选中的项
th:text="${p.name} 表示显示的文本信息是${p.name}

4.遍历单选框

<input name="product" type="radio" th:each="p:${ps}" th:value="${p.id}"  th:checked="${p.id==p.id}"     th:text="${p.name}"  />

说明参考上面

4.4 Swicth

默认属性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>

4.5 URL相关

设置背景

<div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>

根据属性值改变背景

 <div th:style="'background:url(' + @{(${collect.webLogo}=='' ? 'img/favicon.png' : ${collect.webLogo})} + ')'" ></div>

5. 页面布局

实际情况使用布局通常比较复杂,这里只是简单介绍一下布局的使用方式,具体运用要根据实际需要编写不同的布局。
先编写一个用于布局的layout.html文件,内容大概如下:

<body>
<header th:fragment="header">
    head  要显示的模板头部
</header>
  <div th:include="::content">
    这是正文 
</div>
<footer th:fragment="footer">
   foot  要显示的模板尾部
</footer>
</body>

正文html文件:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" th:replace="layout">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
<div th:fragment="content">
   这才是正文
</div>
</body>
</html>

运行的结果大概这样:
在这里插入图片描述
需要注意的正文html文件中的第二行th:replace="layout"是前面编写的layout.html文件
正文中th:fragment=“content"的值要和布局文件中的 th:include=”::content"相对应

6.内置工具

为了模板更加易用,Thymeleaf还提供了一系列Utility对象(内置于Context中),可以通过#直接访问:
Execution Info
Messages
URIs/URLs
Conversions
Dates
Calendars
Numbers
Strings
Objects
Booleans
Arrays
Lists
Sets
Maps
Aggregates
IDs

先说说Dates:
在后端实例化了一个Date对象Date now = new Date();

        直接输出日期 ${now}:
        <p th:text="${now}"></p>
        默认格式化 ${#dates.format(now)}:
        <p th:text="${#dates.format(now)}"></p>
        自定义格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}:
        <p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p>
        直接获取当前时间:
        <p th:text="${#dates.createNow()}"></p>
        直接获取当天时间:
        <p th:text="${#dates.createToday()}"></p>

显示结果:
在这里插入图片描述
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)}

就不一一举例了,有需要的朋友按照具体内置对象百度了解一下吧。

7.Thymeleaf常用标签

关键字操作例子
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:"'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:什么也不做。这个值是有用的动态评估。
th:attr设置标签属性,多个属性可以用逗号分隔比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值