Thymeleaf语法


一、前言

  • Thymeleaf 是什么?
    Thymeleaf 是 Web 和独立环境的现代服务器端 Java 模板引擎,能够处理HTML,XML,JavaScript,CSS 甚至纯文本。
  • 什么是模板引擎?
    模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。
  • 类似的模板引擎有哪些?
    市面上主流的 Java 模板引擎有:JSP、Velocity、Freemarker、Thymeleaf
  • 模板引擎的作用:
    将静态页面和业务数据进行整合,由服务器端渲染之后返回客户端进行显示。不同的模板引擎的区别在于使用不同的语法。
  • 自我认知
    jspthymeleaf,再到vue,这是一个前后端逐渐分离的过程。jsp的特点是页面中可以嵌套java代码,这显然很强大,但导致的结果是页面逻辑(一些前端界面元素的显示隐藏,以及动态变化)和业务逻辑(一些需要访问后台的操作,如数据库查询)常常纠缠在一起,代码混乱不堪,可维护性差,前后台人员职责分工不明确,责任难以追踪。到了thymeleaf,情况好了很多,因为thymeleaf支持html界面,无论是不是在服务器环境下,界面都能展示,在界面上直接与后台交互的情况也少了很多。再到现在很火的vue,才算实现了真正意义上的前后端分离,前端人员专注于前台界面,后端人员专注于后台接口。

二、SpringBoot环境下使用thymeleaf

Springboot整合thymeleaf很简单,下面只介绍下几个步骤:
1.导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.简单配置 application.properties

spring.thymeleaf.enabled=true
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.mode=HTML
spring.thymeleaf.suffix=.html

3.在html界面引入名称空间

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    ......
</html>

三、语法详解

thymeleaf语法都是html标签加th:*的形式

1、 文本操作
//输出字符串 thymeleaf
<h2 th:text="'thymeleaf'"></h2>
//输出字符串 thymeleaf
<h2 th:utext="'thymeleaf'"></h2>

th:text和th:utext的区别:

th:utext中的html标签会正常翻译成html标签,而th:text的内容原样输出。如下:

<p th:text="'hello <b>thymeleaf</b>'"></p> //原样输出
<p th:utext="'hello <b>thymeleaf</b>'"></p>  //thymeleaf加粗

输出包含空格的文本:

<h2 th:text="'thymeleaf home page'"></h2>
<h2 th:utext="|thymeleaf home page|"></h2>

所有th:标签都可以用data-th-替换:

<h2 data-th-text="|thymeleaf home page|"></h2>
<h2 data-th-utext="|thymeleaf home page|"></h2>
2、几种常用符号

#号用于国际化
1.在templates文件夹下建立i18n目录,新建messages_zh_CN.properties文件,内容如下:

thymeleaf.welcome=welcome to thymeleaf index page

2.在application.properties中配置:

spring.messages.basename=i18n/messages

3.在界面中使用:

<p th:text="#{thymeleaf.welcome}"></p>

$用于后端取值

后端要向model存入user对象

<div th:text="${user.name}"></div>

* 用于绑定一个对象的属性,与$结合使用

<span th:object="${human}">
    姓名:<span th:text="*{name}"></span> <br>
    爱好:<span th:text="*{favorite}"></span> <br>
    国籍:<span th:text="*{nationality}"></span> <br>
</span>

@用于链接

<!--引入static/css目录中的thymeleaf.css -->
<link rel="stylesheet" href="../static/css/thymeleaf.css" th:href="@{/css/thymeleaf.css}">

<!--超链接 最终路径为/user/find?username=id-->
<a th:href="@{/user/find(username=${human.name})}">查找用户</a> 

<!--最终路径为:/user/find/具体的username-->
<a th:href="@{/user/find/{username}(username=${human.name})}">查找用户</a> <br>

~用于取到项目根路径

<a th:href="@{~/user/find/jack}">查找用户</a>
3、操作html元素
<!--修改value属性-->
<input type="submit" value="提交" th:value="submit">
<br>

<!--等价于-->
<input type="submit" value="提交" th:attr="value='submit'">
<hr>

<!--除了th:value还有很多其它html元素的属性都可用。-->

<!--追加样式一个addStyle样式-->
<input type="text" class="originStyle" th:classappend="'addStyle'">
<hr>

<!--设置选择状态-->
<input type="checkbox" th:checked="${isChecked}">

4、几种表达式
  • 三元表达式
<div th:object="${user}">
    <div th:text="*{username} == null ? 'username is not defined' : *{username}"></div>
</div>

三元表达式省略写法,表达式为真,值为*{favorite},否则,值为后面的字符串

<div th:object="${user}">
    <div th:text="*{username}?:'username attribute is not defined'"></div>
</div>

三元表达式省略写法,表达式为真,会给标签加上customStyle样式,为假,返回null,什么也不执行

<div th:class="${customStyleOn} ? 'customStyle'"></div>
  • switch表达式
<div th:switch="${usernames.get(1)}">
    username:
    <p th:case="'Lorem'">lorem</p>
    <p th:case="'ipsum'">ipsum</p>
    <p th:case="'dolor'">dolor</p>
    <p th:case="*">whatever</p>  <!--都不匹配时执行-->
</div>
5、条件判断、算数运算
<!--用#引用内置对象判断字符串是否为空-->
<div th:if="${not #strings.isEmpty('lorem')}">lorem</div>

<div th:unless="${ #strings.isEmpty('lorem')}">lorem</div>

<div th:text="33 + 22"></div>

<div th:text="${number} + 22 > 30"></div>
6、循环迭代
<ul>
   <!--遍历user对象,如果是第偶数个则加上自定义样式,如果是奇数,加上详情连接-->
    <li th:each="user : ${users}" th:classappend="${userStat.even}?'m-list-even'">
        <span th:text="${user}"></span>
        <a th:href="@{/user/find/{username}(username=${user})}" th:if="${userStat.odd}">view detail</a>
    </li>
</ul>
7、fragment的使用

fragment类似于jsp的jsp:include,用于重用一些页面。
在templates目录下建立一个footer.html用于存放通用的版权片段:内容如下:

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!--copyright是片段的名字-->
<footer th:fragment="copyright">
    <div>
        &copy;2019-2020 Designed by Oamha, Glad to receive your reply
    </div>
</footer>
</html>

下面就可以将其引入到其它界面中了:

<!--footer是片段所在的文件名,copyright是片段名-->
<div th:insert="footer :: copyright"></div>

<!--上面等价于-->
<div th:insert="~{footer :: copyright}"></div>

<!--引入片段也可以用th:replace-->
<div th:replace="footer :: copyright"></div>

<!--还可以用th:include-->
<div th:include="footer :: copyright"></div>
  • th:insert保留当前页面的div根标签,也保留copyright片段的footer根标签
  • th:replace只保留copyright片段的footer根标签,div被替换掉了
  • th:include保留当前界面的div,但只包含copyright片段的里的内容,不再包含footer根标签

片段还可以传参数:比如有一个navbar片段,所在文件templates/nav.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<div th:fragment="navbar(span, role, username)">
    <span th:replace="${span}"></span>
    <span th:text="${role}"></span>
    <span th:text="${username}"></span>
</div>
</html>

在其他界面引入:

<!--第一个参数传入当前界面的span标签,第二个参数是字符串,第三个参数代表什么也不传-->
<div th:replace="nav :: navbar (~{::span}, 'admin', _)">
    <span>这个span将替换片段中的span</span>
</div>
  • 传当前界面的标签也可以用 ~{this:span}
  • 什么也不传另一种写法为 ~{}
8、注释
<table>
    <!--/*/<th:block th:each="user : ${users}">/*/-->
        <tr>
            <td th:text="${user}">oamha</td>
        </tr>
    <!--/*/</th:block>/*/-->
</table>
  • thymeleaf注释格式为 <!--/*/内容/*/-->
  • 内容部分在浏览器直接打开时会被当成注释,只有在服务器环境下才会被模板引擎正确解析
9、行内表达式
<th:block th:with="str='hello <strong>thymeleaf</strong>'">
    <p>[[${str}]]</p>
    <p>[(${str})]</p>
</th:block>
  • th:block 相当于一个容器,但是不会产生具体的标签
  • th:with 为str变量赋值
  • [[]]相当于th:text
  • [()]相当于th:utext

有时我们需要在JavaScript代码中访问session中的
值,也可以用行内表达式

<!--取出session中的user-->
<script th:inline="javascript">
    var user = [[${session.user}]]
</script>

四、总结

thymeleaf的常用语法就这些,还有一些内置对象的使用,遇到的话可以查阅文档。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM