一、Thymeleaf介绍
thymeleaf是spring boot推荐使用的模板引擎,用于渲染XML/XHTML/HTML5内容的模板引擎,类似JSP,Velocity,FreeMaker等,直接以html显示,它可以轻易的与SpringMVC等Web框架进行集成作为Web应用的模板引擎。,前后端可以很好的分离。
二、Thymeleaf语法
1、在html页面中引入thymeleaf命名空间,即,此时在html,模板文件中动态的属性使用th: 命名空间修饰
这样才可以在其他标签里面使用th:这样的语法.这是下面语法的前提*.
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2、th:任意html属性;来替换原生属性的值
3、th属性,常用属性如下:
1) th:text:文本替换
设置当前元素的文本内容,常用,优先级不高
转义
<p th:text="${共享域中的key值}" />
2) th:utext:支持html的文本替换
和th:text差不多,但是它可以使用html的
不转义
<p th:utext="${thUText}" />
3) th:value:属性赋值
设置当前元素的value值,常用,优先级仅比th:text高
<input type="text" th:value="${thValue}" />
4) th:each:循环遍历元素
<!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入-->
<!--th:each 修饰在div上,则div层重复出现,若只想p标签遍历,则修饰在p标签上-->
<div th:each="message : ${thEach}"> <!-- 遍历整个div-p,不推荐-->
<p th:text="${message}" />
</div>
<div> <!--只遍历p,推荐使用-->
<p th:text="${message}" th:each="message : ${thEach}" />
</div>
5) th:if:条件判断
<!--th:if 条件判断,类似的有th:switch,th:case,优先级仅次于th:each, 其中#strings是变量表达式的内置方法-->
<p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p>
6) th:insert:代码块插入
<!--th:insert 把代码块插入当前div中,优先级最高,类似的有th:replace,th:include,~{} :代码块表达式 -->
<div th:insert="~{grammar/common::thCommon}"></div>
<!--引入侧边栏;传入参数-->
<div th:replace="commons/bar::#sidebar(activeUri='emps')"></div>
三种引入公共片段的th属性:
th:insert:将公共片段整个插入到声明引入的元素中
th:replace:将声明引入的元素替换为公共片段
th:include:将被引入的片段的内容包含进这个标签中
1、引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名(片段名也可以设为属性的ID值)
templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。
2、默认效果:
insert的公共片段在div标签中
如果使用th:insert等属性进行引入,可以不用写~{}:
行内写法可以加上:[[~{}]];[(~{})];
7) th:fragment:定义代码块
1、抽取公共片段
<div th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</div>
copy:是自定义公共片段的名字
注:公共片段也可以设置为属性的ID
8) th:object:声明变量,声明变量,和*{} 一起使用
9) th:attr:设置属性标签
<button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn_del">删除</button>
del_uri:表示自动属性
例子:
<!DOCTYPE html><!--名称空间--><html lang="en" xmlns:th="http://www.thymeleaf.org"><head>
<meta charset="UTF-8">
<title>Thymeleaf 语法</title></head><body>
<h2>ITDragon Thymeleaf 语法</h2>
<!--th:text 设置当前元素的文本内容,常用,优先级不高-->
<p th:text="${thText}" />
<p th:utext="${thUText}" />
<!--th:value 设置当前元素的value值,常用,优先级仅比th:text高-->
<input type="text" th:value="${thValue}" />
<!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入-->
<!--th:each 修饰在div上,则div层重复出现,若只想p标签遍历,则修饰在p标签上-->
<div th:each="message : ${thEach}"> <!-- 遍历整个div-p,不推荐-->
<p th:text="${message}" />
</div>
<div> <!--只遍历p,推荐使用-->
<p th:text="${message}" th:each="message : ${thEach}" />
</div>
<!--th:if 条件判断,类似的有th:switch,th:case,优先级仅次于th:each, 其中#strings是变量表达式的内置方法-->
<p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p>
<!--th:insert 把代码块插入当前div中,优先级最高,类似的有th:replace,th:include,~{} :代码块表达式 -->
<div th:insert="~{grammar/common::thCommon}"></div>
<!--th:object 声明变量,和*{} 一起使用-->
<div th:object="${thObject}">
<p>ID: <span th:text="*{id}" /></p><!--th:text="${thObject.id}"-->
<p>TH: <span th:text="*{thName}" /></p><!--${thObject.thName}-->
<p>DE: <span th:text="*{desc}" /></p><!--${thObject.desc}-->
</div></body></html>
控制器controller:
import com.itdragon.entities.ThObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Controller
public class ThymeleafController {
@RequestMapping("thymeleaf")
public String thymeleaf(ModelMap map) {
map.put("thText", "th:text 设置文本内容 <b>加粗</b>");
map.put("thUText", "th:utext 设置文本内容 <b>加粗</b>");
map.put("thValue", "thValue 设置当前元素的value值");
map.put("thEach", Arrays.asList("th:each", "遍历列表"));
map.put("thIf", "msg is not null");
map.put("thObject", new ThObject(1L, "th:object", "用来偷懒的th属性"));
return "grammar/thymeleaf";
}
}
4、表达式语法:
Simple expressions:(表达式语法)
(1)、Variable Expressions: ${...}:获取变量值;OGNL;
1)、获取对象的属性、调用方法
2)、使用内置的基本对象:
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.
${session.foo}
3)、内置的一些工具对象:
(2)、Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
补充:配合 th:object="${session.user}:
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
(3)、Message Expressions: #{...}:获取国际化内容
(4)、Link URL Expressions: @{...}:定义URL;
4.1、@{…} 链接表达式
链接表达式好处
不管是静态资源的引用,form表单的请求,凡是链接都可以用@{…} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问
#修改项目名,链接表达式会自动修改路径,避免资源文件找不到
server.context-path=/itdragon
链接表达式结构
无参:@{/xxx}
有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2
引入本地资源:@{/项目本地的资源路径}
引入外部资源:@{/webjars/资源在jar包中的路径}
例如:
<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<link th:href="@{/main/css/itdragon.css}" rel="stylesheet">
<form class="form-login" th:action="@{/user/login}" th:method="post" >
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
4.2 、 ${…} 变量表达式
变量表达式功能
一、可以获取对象的属性和方法
二、可以使用ctx,vars,locale,request,response,session,servletContext内置对象
三、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法(重点介绍)
常用的内置对象
一、ctx :上下文对象。
二、vars :上下文变量。
三、locale:上下文的语言环境。
四、request:(仅在web上下文)的 HttpServletRequest 对象。
五、response:(仅在web上下文)的 HttpServletResponse 对象。
六、session:(仅在web上下文)的 HttpSession 对象。
七、servletContext:(仅在web上下文)的 ServletContext 对象
例如:
// java 代码将用户名放在session中
session.setAttribute("userinfo",username);
// Thymeleaf通过内置对象直接获取
th:text="${session.userinfo}"
常用的内置方法
一、strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
二、numbers:数值格式化方法,常用的方法有:formatDecimal等
三、bools:布尔方法,常用的方法有:isTrue,isFalse等
四、arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
五、lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
六、maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
七、dates:日期方法,常用的方法有:format,year,month,hour,createNow等