Thymeleaf
Thymeleaf是什么?
Thymeleaf官网:https://www.thymeleaf.org/
Thymeleaf是一个Java库。它是一个Spring boot推荐使用的XML / XHTML / HTML5模板引擎,直接以html显示,前后端可以很好的分离。能够应用于转换模板文件,以显示您的应用程序产生的数据和文本。它尤其适合于基于XHTML / HTML5的web服务应用程序,同时它可以处理任何XML文件,作为web或独立的应用程序。
Thymeleaf的主要目的是提供一个优雅和格式良好的方式创建模板。为了实现这一目标,它把预定义的逻辑放在XML的标记和属性上,而不是显式放在XML标记的内容上。
依靠智能缓存去解析文件,致使其执行期间的I / O操作达到了最少数量,因此其处理的模板的能力实非常快速的。
Thymeleaf语法:
****必须引入名称空间: xmlns:th="http://www.thymeleaf.org"
1、th属性,常用th属性如下:
1)th:text="${集合/对象.属性}" 文本替换
2)th:utext:支持html的文本替换。
3)th:value=${集合/对象.属性} 属性赋值
4)th:each="xx:${xxList}" 遍历循环元素
5)th:if="${xx.xxx} ==或eq ${xxx.xxxx} "判断条件,类似的还有th:unless,th:switch,th:case
6)th:insert:代码块引入,类似的还有th:replace,th:include,常用于公共代码块提取的场景
7)th:fragment:定义代码块,方便被th:insert引用
8)th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。
9)th:attr:设置标签属性,多个属性可以用逗号分隔
10) th:href="${'/xxx/'+xx.id}" 或者 th:href="@{/xxx/}+${xx.id}" 跳转链接
11) th:text="${#dates.format(xx.xxx),'yyyy-MM-dd HH:mm'}" 时间格式
12) th:selected="${xx.xxx} ==或eq ${xxxx.xxxxx}" 用在option标签设置默认选中
案例:
<!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"; } }

浙公网安备 33010602011771号