SpringBoot Thymeleaf 模板引擎使用

SpringBoot Thymeleaf 模板引擎使用

添加依赖

gradle:

    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

maven:

 <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>
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
  </dependency>

基本使用

Controller:

/**
 * thymeleaf模板引擎
 */
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {

    @GetMapping("/map")
    public String list(Model model) {
        // 这个map在springmvc Context里
        model.addAttribute("k1", "v1");
        model.addAttribute("k2", "v2");
        model.addAttribute("k3", "v3");
        model.addAttribute("k4", "v4");
        model.addAttribute("name", "annamaple");
        Map<String, String> map = new HashMap<>();
        map.put("name", "ming");
        map.put("age", "30");
        model.addAttribute("map", map);
        List<String> list = new LinkedList<>();
        list.add("play");
        list.add("photography");
        list.add("music");
        model.addAttribute("list", list);
        
        List<Map<String, String>> users = new LinkedList<>();
        users.add(map);
        users.add(map);
        users.add(map);
        model.addAttribute("users", users);
        return "thymeleaf";
    }
}

在resources/templates/目录下创建thymeleaf.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>List</title>
</head>
<body>
<!--占位符-->
<h1 th:text="${name}"></h1>
<h2 th:text="${#maps.size(map)}"></h2>
<!--别名-->
<h2 th:object="${map}">
    <p>name: <span th:text="*{name}"></span></p>
    <p>age: <span th:text="*{age}"></span></p>
</h2>
<!--循环-->
<tr th:each="user,stat: ${users}">
    <td th:text="${stat.index}"></td>
    <td th:text="${user.name}"></td>
    <td th:text="${user.age}"></td>
</tr>
<ul th:each="e, stat: ${list}">
    <li th:text="${e}"></li>
</ul>
</body>
</html>

附加知识

兼容处理

  1. 浏览器不支持Html5,如果不支持这种th:的命名空间写法,那么可以把th:text换成 data-th-text,Thymeleaf也可以兼容。th:text指令出于安全考虑,会把表达式读取到的值进行处理,防止html的注入。
    <p>你好</p>将会被格式化输出为$lt;p$gt;你好$lt;/p$lt;。
    
  2. ${user.name} 可以写作$

内置对象

  1. Thymeleaf中提供了一些内置对象

    对象 作用
    #ctx 获取thymeleaf自己的Context对象
    #request 如果是web程序,获取HttpServletRequest对象
    #response 如果是web程序,获取HttpServletResponse对象
    #session 如果是web程序,获取HttpSession对象
    #servletContext 如果是web程序,可以获取HttpServletContext对象
  2. Thymeleaf提供的全局对象

    对象 作用
    #dates 处理java.util.date的工具对象
    #calendars 处理java.util.calendar的工具对象
    #numbers 用来对数字格式化的方法
    #strings 用来处理字符串的方法
    #bools 用来判断布尔值的方法
    #arrays 用来护理数组的方法
    #lists 用来处理List集合的方法
    #sets 用来处理set集合的方法
    #maps 用来处理map集合的方法

逻辑判断

  1. if语句

Thymeleaf中使用th:if 或者 th:unless ,两者的意思恰好相反。

<span th:if="${user.age} > 24">HAHA</span>

说明:如果表达式的值为true,则标签会渲染到页面,否则不进行渲染。

以下情况被认定为true:

  • 表达式值为true

  • 表达式值为非0数值

  • 表达式值为非0字符

  • 表达式值为字符串,但不是"false","no","off"

  • 表达式不是布尔、字符串、数字、字符中的任何一种

  • 其它情况包括null都被认定为false

  1. switch语句
<div th:switch="${user.role}">
  <p th:case="'admin'">用户是管理员</p>
  <p th:case="'manager'">用户是经理</p>
  <p th:case="*">用户是别的玩意</p>
</div>

需要注意的是,一旦有一个th:case成立,其它的则不再判断。与java中的switch是一样的。

另外th:case="*"表示默认,放最后。

JS模板

模板引擎不仅可以渲染html,也可以对JS中的进行预处理。而且为了在纯静态环境下可以运行,其Thymeleaf代码可以被注释起来:

<script th:inline="javascript">
    const user = /*[[${user}]]*/ {};
    const age = /*[[${user.age}]]*/ 20;
    console.log(user);
    console.log(age)
</script>
  • 在script标签中通过th:inline="javascript"来声明这是要特殊处理的js脚本
const user = /*[[Thymeleaf表达式]]*/ "静态环境下的默认值";

因为Thymeleaf被注释起来,因此即便是静态环境下, js代码也不会报错,而是采用表达式后面跟着的默认值。且User对象会被直接处理为json格式。


参考链接:https://www.cnblogs.com/msi-chen/p/10974009.html#_label0_0

posted @ 2022-05-12 11:35  我见青山应如是  阅读(22)  评论(0编辑  收藏  举报