首先是对tymeleaf的初步练习
- 在创建的mavencreate项目中,首先先在resources文件夹下创建templates文件夹,在该文件夹下创建index.html文件
写入以下代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}">默认的title</title>
<meta th:content="${keywords}" name="keywords" content="默认的keywords">
</head>
<body>
hello 第一个Thymeleaf程序
<div th:text="|测试字符串拼接+${name}|">name是test(我是离线数据)</div>
</body>
</html>
直接打开该html页面显示如下:
- 接下来我们尝试使用thymeleaf去动态渲染该html文件
首先要在pom.xml中添加以下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在templates文件夹下新建一个application.properties,添加以下内容
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
server.port=8001
在controller包下新建一个UrlController控制类,写入以下代码
package org.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UrlController {
@GetMapping("/index")//页面的url地址
public String getindex(Model model)//对应函数
{
model.addAttribute("name","test"); //动态替换成test
model.addAttribute("title","thymeleaf的渲染");
return "/index";//与templates中index.html对应
}
}
访问localhost:8001/index,页面显示如下:
常用方法的基础训练BasicTrain
主要尝试了 th:text,th:if,th:switch,th:case
首先先创建了BasicThym类,用来声明变量
package org.example.User;
import lombok.Data;
import java.util.Date;
import java.util.List;
@Data
public class BasicThym {
private String username;
private Integer age;
private Integer gender;
private Boolean isVip;
private Date createTime;
public List<String> tags;
}
在templates文件夹下创建了Basic.html文件
<!DOCTYPE html>
<html lang="ch" xmlns:th="https://www.thymeleaf.org">
<head