Springboot(五)——thymeleaf模板引擎
thymeleaf模板引擎
一、導(dǎo)入thymeleaf依賴或者在創(chuàng)建項(xiàng)目的時(shí)候勾選thymeleaf模板引擎
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
二、根據(jù)源碼,我們使用thymeleaf模板的時(shí)候,需要將html放在templates目錄下
在templates目錄下的所有頁面,只能通過controller跳轉(zhuǎn)!
并且需要模板引擎的支持!thymeleaf
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
thymeleaf使用
一、編寫controller
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","hello,springboot");
return "test";
}
二、在templates目錄下新建test.html
<!DOCTYPE html>
<!--注:這里一定要引入頭文件-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--th:text 取出的值被轉(zhuǎn)義成text-->
<div th:text="${msg}"></div>
</body>
</html>
三、運(yùn)行測(cè)試
thymeleaf語法
一、controller編寫
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","<h1>hello,springboot</h1>");//加群1025684353一起吹水聊天
model.addAttribute("users", Arrays.asList("zhangsan","lisi"));
return "test";
}
二、html修改
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--th:text 標(biāo)注這個(gè)值是test-->
<div th:text="${msg}"></div>
<!--不轉(zhuǎn)義-->
<div th:utext="${msg}"></div>
<hr>
<!--遍歷集合-->
<h3 th:each=" user:${users}" th:text="${user}"></h3>
<!--遍歷集合方式二:沒有提示-->
<h3 th:each=" user:${users}" >[[${user}]]</h3>
<hr>
</body>
</html>
三、運(yùn)行測(cè)試結(jié)果
白嫖資料
thymeleaf語法糖
基礎(chǔ)語法
- 普通變量:${}
- 國際化消息:#{}
- url鏈接@{}
- 判斷表達(dá)式~{}
- 文本:'test'(單引號(hào))
三元條件運(yùn)算符
- if-then:(if)?(then)
- if-then-else:(if)?(then):(else)
- Defult:(value)?:(defultvalue)


