springBoot的模版引擎

119 阅读1分钟

模版引擎

常见的模版引擎有JSP、Velocity、Freemarker和Thymeleaf

Thymeleaf模版

  • 使用时需要把html页面放在classpath:/templates/文件夹下,thymeleaf就能自动渲染

  • 创建模版文件,并需要导入thymeleaf的名称空间

    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    
  • 使用模版

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>[[${title}]]</title>
    </head>
    <body>
    <h1 th:text="${title}"></h1>
    <div th:text="${info}">这里的文本之后将会被覆盖</div>
    </body>
    </html>
    
  • 在controller里面准备模版需要的数据

    @Controller
    public class HelloT {
    
        @RequestMapping("/ht")
        public String ht(Model model) {
            model.addAttribute("title","hello Thymeleaf")
                 .addAttribute("info","this is first thymeleaf test");
            return "t1";
        }
    }
    

语法规则

th:text --》改变元素里面的文本内容

th:任意的html属性 --》替换原生的属性的值;html属性值只要加上了th:就相当于兼容了Thymeleaf模版