Spring Boot -- Thymeleaf

Thymeleaf简介

Thymeleaf最大的特点是使用的H5,可以直接打开页面,不需要启动整个Web应用程序。

1. pom.xml

<!-- thymeleaf -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <optional>true</optional>
</dependency>

2. application.properties

Thymeleaf的默认配置

# THYMELEAF (ThymeleafAutoConfiguration)
#开启模板缓存(默认值:true)
spring.thymeleaf.cache=true
#在呈现模板之前检查模板是否存在
spring.thymeleaf.check-template=true
#检查模板位置是否正确(默认值:true)
spring.thymeleaf.check-template-location=true
#Content-Type的值(默认值:text/html)
spring.thymeleaf.content-type=text/html
#开启MVC Thymeleaf视图解析(默认值:true)
spring.thymeleaf.enabled=true
#模板编码
spring.thymeleaf.encoding=UTF-8
#要被排除在解析之外的视图名称列表,用逗号分隔
spring.thymeleaf.excluded-view-names=
#要运用于模板之上的模板模式。另见StandardTemplate-ModeHandlers(默认值:HTML5)
spring.thymeleaf.mode=HTML5
#在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/)
spring.thymeleaf.prefix=classpath:/templates/
#在构建URL时添加到视图名称后的后缀(默认值:.html)
spring.thymeleaf.suffix=.html
#Thymeleaf模板解析器在解析器链中的顺序。默认情况下,它排第一位。顺序从1开始,只有在定义了额外的TemplateResolver Bean时才需要设置这个属性。
spring.thymeleaf.template-resolver-order=
#可解析的视图名称列表,用逗号分隔
spring.thymeleaf.view-names=

常用配置

#常用配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=true
spring.thymeleaf.enabled=true

3.创建Thymeleaf

在resources\templates目录下创建html,并在html标签中添加命名空间xmlns:th=”http://www.thymeleaf.org
在这里插入图片描述

<!DOCTYPE html>
<html lang="en" xml:th="http://www.thymeleaf.org">
<head>

4.Thymeleaf的基本操作

1.表达式

${}变量表达式,用于访问容器上下文环境中的变量,功能同jstl中${}

<span th:text="${name}"></span>

*{}选择表达式,选择表达式与变量表达式有一个重要的区别:选择表达式计算的是选定的对象,而不是整个环境变量映射。也就是:只要是没有选择的对象,选择表达式与变量表达式的语法是完全一样的

request.setAttribute("name", "Thymeleaf");
User user = new User();
user.setName("spring boot");
request.setAttribute("user", user);
<!-- 变量表达式 -->
<span th:text="${name}"></span><br>
<!-- 选择表达式 没有指定对象 和${}一样 -->
<span th:text="*{name}"></span>

<!-- 指定对象的*{} 取的是user里的name -->
<div th:object="${user}">
    <span th:text="*{name}"></span>
</div>

<!-- 
页面输出
Thymeleaf
Thymeleaf
spring boot
--->

#{}消息表达式.国际化时使用,也可以使用内置的对象,比如date格式化数据

@{…}链接表达式,用来配合link src href使用的语法

<!-- 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

~{…}片段表达式,用来引入公共部分代码片段,并进行传值操作使用的语法


2.文本操作

<!-- 结果: Welcome to our application, xubo!  -->
<span th:text="|Welcome to our application, ${user.name}!|">

|…|中只能包含变量表达式${…},不能包含其他常量、条件表达式等

格式化文本操作

request.setAttribute("msg", "<b>123</b>");
<span th:text="${msg}"></span>
<br>
<span th:utext="${msg}"></span>

th:text输出: <b>123</b>
th:utext将html标签渲染后输出,输出黑体的123


3.运算符

算术运算符: +, -, *, /, %
逻辑运算符:
> , < , >= , <= ( gt , lt , ge , le )
== , != ( eq , ne )
and or ! not


4.遍历

th:each

<div class="row" >
    <div th:each="item, stat : ${links}">
        <div class="col-md-2"  th:title="${item.description}">
            <strong th:text="${item.link_name}"></strong>
            <a href="#" th:href="${item.link}" th:text="${item.link}" >超链接</a>
        </div>
    </div>
</div>

item为迭代对象
stat称作状态变量,属性有:

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

${list}为迭代集合


5.条件判断

<tbody>
<tr th:each="test:${test}">
    <!--判断成绩-->
    <td th:if="${test.Score} gt 0 and ${test.Score} lt 60"></td>
    <td th:if="${test.Score} ge 60 and ${test.Score} le 70"></td>
    <td th:if="${test.Score} gt 70 and ${test.Score} le 80"></td>
    <td th:if="${test.Score} gt 80 and ${test.Score} le 90"></td>
    <td th:if="${test.Score} gt 90 and ${test.Score} le 100">超级优秀</td>
</tr>
<br>
<tr th:each="test:${test}">
    <!--判断成绩   一般只有两种情况的时候可以使用这种方式-->
    <td th:if="${test.Score} gt 0 and ${test.Score} lt 60"></td>
    <!--除了这些条件之外的-->
    <td th:unless="${test.Score} gt 0 and ${test.Score} lt 60">及格</td>
</tr>
<tr th:each="test:${test}">
    <td th:switch="${test.male}">
        <span th:case="1"></span>
        <span th:case="2"></span>
        <!--其他情况-->
        <span th:case="*">未知</span>
    </td>
</tr>
</tbody>

单条件判断使用th:if
if…else…判断时使用th:if, th:unless
多条件判断使用th:swich, th:case


6.Thymeleaf内置对象和其他常见操作

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

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

日期格式化

<td th:text="${#dates.format(createDate,'yyyy-MM-dd HH:mm:ss')}"></td>

字符截取长度

<td th:text="${#strings.substring(str,0,5)}"></td>

数组判断是否为空

<div th:if="${#lists.isEmpty(arrays)} "></div>

request 获取绝对路径

<img th:src="${#httpServletRequest.getContextPath()}" />

下拉选择

<select name="subId" id="subId" lay-verify="" >
    <option value="">请选择</option>
    <option th:each="channelsub:${subchannels}" th:selected="${channelsub.id == subId}"    th:value="${channelsub.id}" th:text="${channelsub.name}"></option>
</select>

js取值

<script th:inline="javascript">
    var size= [[${list.size()}]];
</script>

css取值

<style th:inline="css">
    .[[${classname}]] {
        text-align: [[${align}]];
    }
</style>

模板引用

<!-- 底部模板 -->
<div th:fragment="footer">
    © 2018 xxx
</div>
<!-- 引用底部模板 -->
<div th:include="/footer :: footer"></div>

7.常用th标签

标签 说明 代码
th:id 替换id <input th:id="${id}" />
th:text 替换文本 <span th:text="${name}"></span>
th:utext 支持html标签的替换文本 <span th:utext="${msg}"></span>
th:object 替换对象 <div th:object="${users}"></div>
th:value 表单赋值 <input th:value="${value}" />
th:with 变量赋值运算 <div th:with="isEven=${count}%2 == 0"></div>
th:style 设置样式 <div th:style="'width:' + ${width}"></div>
th:onclick 点击事件 <div th:onclick="'getClick()'"></div>
th:each 遍历 <tr th:each="obj, objStart : ${list}"></tr>
th:if 条件判断 <tr th:if="${num == 3}"></tr>
th:unless 与if判断相反 <tr th:unless="${num == 3}"></tr>
th:switch switch选择,与case配合使用 <div th:switch="${id}"></div>
th:case case分支语句,和switch配合使用 <span th:case="1">男</span>
th:href 替换链接 <a th:href="@{/login}"></a>
th:fragment 布局标签,定义一个代码片段,用于引用 <div th:fragment="code"></div>
th:include 布局标签,替换内容为引用的代码 <div th:include="common :: code"></div>
th:replace 布局标签,替换整个标签为引用的代码 <div th:replace="common :: code"></div>
th:selected select下拉框选中 <option th:selected="${id == 4}"></option>
th:src 资源路径替换 <img th:src="@{/images/title.jpg}" />
th:inline 定义js脚本使用变量 <script th:inline="javaScript" />
th:action 替换表单提交地址 <form th:action="@{/save}"></form>
th:remake 删除标签 <div th:remake="all"></div>
th:attr 设置标签属性,多个属性使用逗号分隔 <div th:attr="style='${width}', title='${title}'"></div>

热部署

在idea中Thymeleaf热部署方式:
1.将缓存修改为false spring.thymeleaf.cache=false
2.修改html页面后进行重新编译 ctrl + shift + F9

猜你喜欢

转载自blog.csdn.net/lolwsyzc/article/details/83106288
今日推荐