美文网首页
Thymeleaf静态化

Thymeleaf静态化

作者: menghuijia | 来源:发表于2018-09-06 15:57 被阅读0次

首先在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>

相关文章

网友评论

      本文标题:Thymeleaf静态化

      本文链接:https://www.haomeiwen.com/subject/qfpxgftx.html