SpringBoot整合Thymeleaf模版

1、Thymeleaf简介

SpringBoot推荐使用Thymeleaf替代Jsp。Tymeleaf是一款用于渲染XML/XHTML/HTML5内容的模版引擎,Tymeleaf最大的特点是能够直接在浏览器中打开并正确显示模版页面,而不需要启动整个Web应用。Tymeleaf使用了自然的模版技术,其模版语法并不会破坏文档的结构,Tymeleaf会在运行期替换掉静态值,模版依旧是有效的XML文档。
下面的代码示例分别使用 Velocity、FreeMarker 与 Thymeleaf 打印出一条消息:

Velocity: <p>$message</p>
FreeMarker: <p>${message}</p>
Thymeleaf: <p th:text="${message}">Hello World!</p>

注意,由于 Thymeleaf 使用了 XML DOM 解析器,因此它并不适合于处理大规模的 XML 文件。

2、Thymeleaf的使用

1)引入Thymeleaf

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2)SpringBoot已经为我们自动配置好了thymeleaf,所有配置值都在 ThymeleafProperties.class直接使用即可。
在这里插入图片描述
默认只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染。使用时必须在页面引入thymeleaf的名称空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

创建index.html页面

<!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>

3)在Controller中准备数据

package com.example.springboot_demo.controller;

import com.example.springboot_demo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorldController {
    @GetMapping("/index")
    public String ht(Model model){
        model.addAttribute("title","hello thymeleaf").addAttribute("info","this is frist thymeleaf page");
        return "index";
    }

}

页面开发使用@Controller注解即可,至此整合Thymeleaf完成启动项目。
4)语法规则
th:text --> 改变当前元素里面的文本内容;
th:任意html属性 --> 来替换原生属性的值

属性优先级:
在这里插入图片描述
更多配置参考官方文档:https://www.thymeleaf.org/documentation.html
中文参考书册:https://www.lanzous.com/i7dzr2j

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值