1、Thymeleaf简介
Thymeleaf是个XML/XHTML/HTML5模板引擎,能够用于Web与非Web运用
Thymeleaf的重要目的在于供应一种可被浏览器准确显现的、花样优越的模板建立体式格局,因而也能够用作静态建模,Thymeleaf的可扩展性也异常棒。你能够运用它定义本身的模板属性鸠合,如许就能够盘算自定义表达式并运用自定义逻辑,Thymeleaf还能够作为模板引擎框架。
2、引入Thymeleaf
引入依靠在maven(pom.xml)中直接引入:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>设置Thymeleaf
在application.yml设置Thymeleaf
server: port: 8000 spring: thymeleaf: cache: false # 封闭页面缓存 encoding: UTF-8 # 模板编码 prefix: classpath:/templates/ # 页面映照途径 suffix: .html # 试图后的后缀 mode: HTML5 # 模板形式 # 其他细致设置可参考org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties # 上面的设置实际上就是注入该类的属性值demo示例
建立IndexController
@Controller public class IndexController { // 返回视图页面 @RequestMapping("index") public String index(){ return "index"; } }
建立index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Hello Thymeleaf! </body> </html>
建立TestController
@RestController public class TestController { // 返回全部页面 @RequestMapping("/test") public ModelAndView test(){ return new ModelAndView("test"); } }
建立test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Hello Thymeleaf! </br> By: ModelAndView </body> </html>
4、Thymeleaf基本语法及运用
引入标签
html标签里引入xmlns:th="http://www.thymeleaf.org"才运用th:*如许的语法
引入URL
@{...}
比方:
<a th:href="@{http://www.baidu.com}">绝对途径</a> 是接见绝对途径下的URL, <a th:href="@{/}">相对途径</a> 是接见相对途径下的URL。 <a th:href="@{css/bootstrap.min.css}">是引入默许的static下的css文件夹下的bootstrap文件,相似的标签有: th:href 和 th:src
3.猎取变量
经由过程${}取值,关于JavaBean的话,运用变量名.属性名猎取
4.字符串替代
<span th:text="'Welcome to our application, ' + ${user.name} + '!'"></span> 或许 <span th:text="|Welcome to our application, ${user.name}!|"></span> 注重:|…|中只能包括变量表达式${…},不能包括其他常量、前提表达式等
5.运算符
在表达式中能够运用各种算术运算符
比方 (+, -, *, /, %)
比方:th:with="isEven=(${stat.number} % 1 == 0)"
逻辑运算符 (>, <, <=,>=,==,!=)
须要注重的是运用<,>的时刻须要转义
th:if="${stat.number} > 1" th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
6.前提
if/unless th:if是该标签在满足前提的时刻才会显现,unless是不成立时刻才显现
<a th:href="@{/login}" th:unless=${user.number != null}>Login</a>
switch thymeleaf支撑switch构造,默许属性(default)用*示意
<p th:switch="${user.role}"> <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> <p th:case="*">User is some other thing</p> </p>
7.轮回
<tr th:each="prod : ${prods}"> <td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.inStock}? #{true} : #{false}">yes</td> </tr>
8.Utilities
内置在Context中,能够直接经由过程#接见 #dates #calendars #numbers #strings arrays lists sets maps …
5.小结
本文报告了如安在Spring Boot中引入模板引擎Thymeleaf以及Thymeleaf基本语法和实际运用
【相干引荐:Java视频教程】
以上就是SpringBoot引入Thymeleaf的要领引见(代码)的细致内容,更多请关注ki4网别的相干文章!