Thymeleaf静态化

首先在spring boot项目依赖spring-boot-starter-thymeleaf

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
  • 添加上述依赖Spring会自动注入org.thymeleaf.spring5.SpringTemplateEngine
package com.meng.thymeleaf.web;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

@RestController
@AllArgsConstructor
@Slf4j
public class IndexController {

    private TemplateEngine templateEngine;

    @GetMapping(value = "", produces = MediaType.TEXT_HTML_VALUE)
    public String index(Model model) {
        model.addAttribute("title", "thymeleaf");
        model.addAttribute("name", "Hello Thymeleaf");
        Context context = new Context();
        context.setVariables(model.asMap());
        String result = templateEngine.process("index", context);
        log.info("{}", result);
        return result;
    }

}
  • Context为上下文
  • 静态化之后我们可以使用放入缓存中

输出内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf</title>
</head>
<body>
    <h1>Hello Thymeleaf</h1>
</body>
</html>

模板文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="${title}">Title</title>
</head>
<body>
    <h1 th:text="${name}"></h1>
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容