SpringBoot之模板引擎

1. 什么是模板引擎

将模板文件和数据通过模板引擎生成一个HTML代码

jsp就是一个模板引擎,还有用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf。
在这里插入图片描述
图来源于:https://www.jianshu.com/p/e4aa40458dfd

2. 为什么要用模板引擎

SpringBoot这个项目首先是以jar的方式,不是war,而且还是用嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的

3. 常见的模板引擎

  • JSP

  • Thymeleaf

  • Velocity

  • Freemarker

    模板引擎比较:https://blog.csdn.net/az44yao/article/details/99887733

4. 引入Thymeleaf

Thymeleaf 官网:https://www.thymeleaf.org/
Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf
Spring官方文档:找到我们对应的版本
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter

  1. 导入依赖
<!--模板引擎:thymeleaf-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 编写controller类
@Controller
public class HelloController {
    @GetMapping("/test")
    public String test(Model model) {
        model.addAttribute("msg","Hello SpringBoot");
        return "test";
    }
}
  1. 编写在resources下的templates建立test.html

注意:

  • 使用前需引入约束
<html lang="en" xmlns:th="http://www.thymeleaf.org">
  • 所有的htmL元素都可以被thymeLeaf替换接管: th:元素名
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--所有的htmL元素都可以被thymeLeaf替换接管: th:元素名-->
<div th:text="${msg}"></div>
</body>
</html>
  1. 测试
    在浏览器输入:http://localhost:8080/test
    在这里插入图片描述

5. Thymeleaf语法

在这里插入图片描述

5.1 th:text与th:utext

<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>

测试:
在这里插入图片描述

5.2 th:each

两种方式:推荐使用第一种

<div th:each="user:${users}" th:text="${user}"></div>
<div th:each="user:${users}">[[${user}]]</div>

测试:
在这里插入图片描述
Thymeleaf使用(参考博客):https://www.cnblogs.com/jerry126/p/11531310.html

参考内容:https://www.bilibili.com/video/BV1PE411i7CV
仅用于学习!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值