做了几年的java web开发,我使用最多的模板引擎应该是freemarket和JSP了,不过最近公司开始引入springboot作为开发的框架,这让我接触到了一个新的模板引擎,也就是thymeleaf(读音:/taim li:f/)。
其实thymeleaf模板引擎其实网上已经有很多成熟的资料,不过我还是喜欢自己做一下笔记,毕竟自己的笔记自己看了最明了了。
英语好的朋友可以直接去官网下载最新的文档,内容非常的全,只是我英语不好,看的比较吃力。
概念
thylemeaf是一个JAVA模板引擎,能完全取代JSP。是一个自然的模板引擎,原型即页面,方便前端和后台开发同时调试。支持OGNL、SpringEL表达式,语法优雅且易懂。
如何使用
这里暂且只介绍springboot框架下的使用
maven 添加依赖包
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
gradle 添加依赖
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
添加完依赖之后,在页面上引入命名空间 即可使用
<html xmlns:th="http://www.thymeleaf.org" >
项目结构如下:
具体语法
-
取值:
thylemeaf表达式 HTML5写自定义属性的标准方式 th:text=”...” th:utext="...' data-th-text="..."
使用方法如下,两者效果是一致的:
<p th:text="${htmlContent}">www.baidu.com</p> <p th:utext="${htmlContent}">www.baidu.com</p> <p data-th-text="${htmlContent}">www.baidu.com</p>
-
标准表达式:
1、变量表达式:语法:${…}
<p th:text="${user.name}">王五</p> <p th:text="${user.getName()}">王五</p> <p th:text="我的名字是+ ${user.name}">王五</p> <p th:text="|我的名字是 ${user.name}|">王五</p>
虽然页面上写着是王五,但controller里面设置了user.setName(“张三”),所以页面上显示的结果就是张三,不过如果是以静态页面方式打开,那页面就会显示王五了。
2、消息表达式:语法:#{…}
<!-- /* 消息表达式 */ --> <div> <p th:text="#{message.content}"></p> <p th:text="#{message.welcome(${userModel.user.name})}"></p> </div>
3、选择表达式:语法:*{…}
<!-- /* 选择表达式 */ --> <div th:object="${userModel.user}"> <span th:text="*{name}"></span> </div> <div> <span th:text="*{userModel.user.name}"></span> </div>
4、链接表达式:语法:@{…}
<!-- /* 链接表达式 */ --> <div> <a href="www.baidu.com" th:href="@{/users/thtest}">链接表达式</a> </div>
5、分段表达式:语法:th:insert或者th:replace
<div th:replace="~{fragments/footer :: footer}"></div>
6、字面量:
文本:
<span th:text="我是张三"></span
数字:
<span th:text="100+15"></span>
布尔:
<div th:if="${isTrue}==false">
NULL:
<div th:if="${name}==null">
7、算法操作:
加、减、乘、除、取余等基本算法8、比较和等价
> < >= <= gt lt ge le == != eq ne
9、条件运算符
?:10、无操作
_ -
设置属性值:
1、设置任意属性值th:attr <form action="subscribe.html" th:attr="action=@{/subscribe}"> <input type="submit" value="subscribe!" th:attr="value=${subscribe.submit}">
2、设置值到指定的属性
<form action="subscribe.html" th:action="@{/subscribe}"> <input type="submit" value="subscribe!" th:value="${subscribe.submit}">
3、固定值布尔属性
HTML th:checked="${user.active}" XHTML checked="checked"
这一篇就先写到这里,文章太长了看着就会失去耐心,还有一些内容另外再写一篇文章好了。