Springboot Thymeleaf

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Springboot Thymeleaf

奔走的王木木Sir   2022-09-08 我要评论

模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎

如果我们没有模板引擎的话,在页面中会提示500

引入Thymeleaf

在项目中加入依赖

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

Thymeleaf 官网:https://www.thymeleaf.org/

Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf

Spring官方文档:找到我们对应的版本

https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/htmlsingle/#using-boot-starter

我们可以有通过上述的页面找到我们需要的依赖,进而复制粘贴即可。

引入之后我们再次运行。nice

注意: 使用Thymeleaf,只需要导入对应的依赖即可。同时我们的html页面试放在我们的templates目录下的。

至于为什么,我们看源码,这段源码在ThymeleafProperties下。

private String prefix = "classpath:/templates/";
private String suffix = ".html";

取值

那么我们应该怎么取值呢

首先在controller下编写代码

@Controller
public class HelloController {
    @RequestMapping("/test")
    public String hello(Model model){
        model.addAttribute("msg","王木木");
        return "test";
    }
}

接下来我们在html页面中编写

因为我们要使用thymeleaf,需要在html文件中导入命名空间的约束。

<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>
<div th:text="${msg}"></div>
</body>
</html>

成功运行后

这里需要这个的th标签。所有的html元素都科一被thymeleaf替换接管,格式为th:元素名

有无转义

从controller传一段信息

model.addAttribute("msg","<h1>王木木</h1>");

html中使用转义和不转义的情况

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

运行结果

循环

同样在controller里传一段信息

model.addAttribute("users", Arrays.asList("wangmumu","王木木"));

接下来在html中进行取值

<h2 th:each="user:${users}" th:text="${user}"></h2>

运行结果

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们