thymeleaf中的一些符号的运用与在html中的标签
参考官网:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf
创建一个thymeleaf项目
或者直接在原来的项目中导入thymeleaf依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
在springboot项目中html文件所放的位置
然后来一个controller
package com.zkw.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Arrays;
@Controller
public class HelloController {
@RequestMapping("/test")
public String TestHello(Model model){
model.addAttribute("msg","<h1>这是一个测试模板引擎<h1>");
model.addAttribute("msg1","<h1>这是一个测试模板引擎<h1>");
model.addAttribute("books", Arrays.asList("数据结构","水浒传","红楼梦","西游记","三国演义"));
return "test";
}
@RequestMapping("/index")
public String TestIndex(){
return "index";
}
}
注意:在使用Thymeleaf时,html页面需要导入
xmlns:th="http://www.thymeleaf.org
<span th:insert="~{public :: head}"></span>
解释:public是公共页面的名字也就是public.html,head是名字th:fragment="head"
th:text=""、th:utext=""
解释:utext可以解析java代码中的标签,而text没有这个功能
然后来一个test页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<span th:insert="~{public :: head}"></span>
<hr/>
<span th:text="${msg}"></span>
<span th:utext="${msg1}"></span>
<hr/>
<div th:each="book:${books}" th:switch="${book}">
<span th:case=" '红楼梦' " th:text="${book}+是四大名著" ></span>
<span th:case="*" th:text="${book}"></span>
</div>
</body>
</html>
公共页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<header th:fragment="head" ><h1>这是头部</h1></header>
</div>
</body>
</html
结果如下