简介
Thymeleaf是一个现代的服务器端 Java 模板引擎,适用于 Web 和独立环境。
Thymeleaf 的主要目标是为您的开发工作流程带来优雅的自然模板——HTML可以在浏览器中正确显示,也可以用作静态原型,从而在开发团队中实现更强大的协作。
借助 Spring Framework 的模块、与您最喜欢的工具的大量集成以及插入您自己的功能的能力,Thymeleaf 是现代 HTML5 JVM Web 开发的理想选择——尽管它可以做的更多。
官网及教程
官网:https://www.thymeleaf.org/index.html
上手教程:https://www.jianshu.com/p/8dc48fa74e7e
实用教程:https://www.jianshu.com/p/908b48b10702
官方教程:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
1、变量表达式${}
2、选择变量表达式 *{} 推荐使用!
3、链接表达式 @{}
4、片段表达式 ~{}
5、消息表达式 #{}
6、其它表达式
基础语法
1、变量表达式${}
使用方法:直接使用th:xx = “${}” 获取对象属性 。
<form id="userForm">
<input id="id" name="id" th:value="${user.id}"/>
<input id="username" name="username" th:value="${user.username}"/>
<input id="password" name="password" th:value="${user.password}"/>
</form>
<div th:text="hello"></div>
<div th:text="${user.username}"></div>
2、选择变量表达式 *{} 推荐使用!
使用方法:首先通过th:object 获取对象,然后使用th:xx = "*{}"获取对象属性。
<form id="userForm" th:object="${user}">
<input id="id" name="id" th:value="*{id}"/>
<input id="username" name="username" th:value="*{username}"/>
<input id="password" name="password" th:value="*{password}"/>
</form>
3、链接表达式 @{}
通过链接表达式@{}直接拿到应用路径,然后拼接静态资源路径。
<script th:src="@{/webjars/jquery/jquery.js}"></script>
<link th:href="@{/webjars/bootstrap/css/bootstrap.css}" rel="stylesheet" type="text/css">
4、片段表达式 ~{}
片段表达式是Thymeleaf的特色之一,细粒度可以达到标签级别,这是JSP无法做到的。
片段表达式拥有三种语法:
- ~{ viewName } 表示引入完整页面
- ~{ viewName ::selector} 表示在指定页面寻找片段其中selector可为片段名、jquery选择器等
- ~{ ::selector} 表示在当前页寻找
使用方法:首先通过th:fragment定制片段 ,然后通过th:replace 填写片段路径和片段名。例如:
<!-- /views/common/head.html-->
<head th:fragment="static">
<script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
</head>
<!-- /views/your.html -->
<div th:replace="~{common/head::static}"></div>
在实际使用中,我们往往使用更简洁的表达,去掉表达式外壳直接填写片段名。例如:
<!-- your.html -->
<div th:replace="common/head::static"></div>
值得注意的是,使用替换路径th:replace 开头请勿添加斜杠,避免部署运行的时候出现路径报错。(因为默认拼接的路径为spring.thymeleaf.prefix = classpath:/templates/)
5、消息表达式 #{}
即通常的国际化属性:#{msg} 用于获取国际化语言翻译值。例如:
<title th:text="#{user.title}"></title>
6、其它表达式
在基础语法中,默认支持字符串连接、数学运算、布尔逻辑和三目运算等。例如:
<input name="name" th:value="${'I am '+(user.name!=null?user.name:'NoBody')}"/>