Springboot 整合 Thymeleaf

时间:2021-07-21
本文章向大家介绍Springboot 整合 Thymeleaf,主要包括Springboot 整合 Thymeleaf使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Springboot 整合 Thymeleaf

1.什么是Thymeleaf

Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎。相较与其他的模板引擎,它有一个最大的特点是,它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服 务器查看带数据的动态页面效果。 这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板 +数据的展示方式。

<a th:text="${url}">百度</a> 

浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以 静态地运行; 当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

2.快速开始

1)引入依赖
<dependency> 
		<groupId>org.springframework.boot</groupId> 
		<artifactId>spring-boot-starter-thymeleaf</artifactId> 
</dependency>

2)配置Thymeleaf模版参数
spring: 
  thymeleaf: 
    cache: false

3)创建模版文件 hello.html

文件存放的位置:resource/templates

<!DOCTYPE html> 
<html xmlns:th="http://www.thymeleaf.org"> 
   <head> 
      <meta charset="UTF-8"></meta> 
      <title>Insert title here</title> 
   </head> 
   <body>Welcome <span th:text="${uname}">Admin</span>! </body> 
</html>

接口设置

@Controller
public class UserController {


    @RequestMapping("/userlist")
    public String userList(Model model){

        User user1 = new User();
        user1.setUname("小李");
        user1.setUid(1L);
        user1.setAge(20);
        user1.setEntryDate(new Date());

        User user2 = new User();
        user2.setUname("小王");
        user2.setUid(2L);
        user2.setAge(21);
        user2.setEntryDate(new Date());

        User user3 = new User();
        user3.setUname("小赵");
        user3.setUid(3L);
        user3.setAge(22);
        user3.setEntryDate(new Date());

        List<User> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);
        users.add(user3);

        model.addAttribute("users",users);
//        model.addAttribute("user",user);
        return "userlist";
    }



    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("uname","小明");
        return "hello";
    }

}

3.Thymeleaf中的小技巧

1)字符串
欢迎:<span th:text="${username}"></span><br/> 
欢迎:<span th:text="超级VIP+${username}"></span><br/> 
欢迎:<span th:text="|超级VIP,${username}|"></span><br/>

2)条件判断
# 条件为真,则显示所处的年龄段 
<span th:if="${age > 18}">老腊肉</span>
<span th:if="${age <= 18}">小鲜肉</span>

# 条件不为真,则显示
<span th:unless="${age>18}" th:text="未超过18岁"></span>

3)三元运算符
<span th:text="${age>18 ? '不年轻了':'too yong'}"></span>

4)循环
<table>
   <tr>
      <td>id</td> 
      <td>姓名</td> 
   </tr> 
   <tr th:each="stu : ${stus}"> 
      <td th:text="${stu.id}">id</td> 
      <td th:text="${stu.name}">姓名</td> 
   </tr>
</table>

5)日期格式化
<input th:value="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"/>

原文地址:https://www.cnblogs.com/qxlzzj/p/15039301.html