SpringBoot(Web开发——Thymeleaf模板引擎入门)

什么是 Thymeleaf?

  SpringBoot建议使用HTML来完成动态页面。SpringBoot提供了大量的模板引擎,其中包括Thymeleaf、FreeMarker、Velocity等

  SpringBoot官方推荐使用Thymeleaf模板引擎来完成动态页面,并且为Thymeleaf提供了完美的SpringMVC的支持,Thymeleaf模板引擎可以支持纯HTML浏览器展现(模板表达式在脱离运行环境下不会污染HTML结构),感兴趣的朋友可以自行百度了解一下,这里不做详细介绍

导入Thymeleaf 依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf 语法

使用thymeleaf之前需要引入,如下

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

这样就可以在其他标签里面使用 th:* 这样的语法

渲染连接

thymeleaf对于URL的处理是通过语法 @{*} 来处理的

<a th:href="@{http://www.baidu.com}">百度一下</a> <!--链接-->

<a th:href="@{css/bootstrap.css}">CSS样式</a> <!--CSS静态-->
渲染字符串

正常显示数据

<p th:text="这里是p标签"></p>

通过后台传过来的数据,需要使用 $ 符号,然后值用花括号括起来

<p th:text="x"></p>

也可以拼接字符串,如:

<p th:text=" '这里是p标签' + ${后台数据} "></p>
运算

在表达式中可以使用各类算舒服,如+、-、*、/、%:

<p th:with="result=(100 % 2 == 0)"></p>
循环遍历

thymeleaf中循环遍历集合使用的是 th:each 标签,可以迭代的对象可以为 List、Map或数组等,用法如下:

<tr th:each="user:${user}">
	<td th:text="${user.id}">1</td>
	<td th:text="${user.name}">Jhon</td>
	<td th:text="${user.age}">18</td>
</tr>

SpringBoot整合Thymeleaf 例子

导入web依赖

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

控制器代码如下:

@Controller
public class HelloController {

    @RequestMapping("/user")
    public String user(Model model){
        Map<Integer,String> map = new HashMap<>();
        map.put(1,"John");
        map.put(2,"Kingdom");
        map.put(3,"Lisa");
        model.addAttribute("map",map);
        return "user";
    }

}

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="${map}"></h1>
</body>
</html>

application.properties配置一下

server.port = 8080												#访问端口
spring.thymeleaf.prefix = classpath:/templates/  #默认访问该目录下的hmtl页面
spring.thymeleaf.suffix = .html                  			#去掉后缀

在这里插入图片描述

发布了184 篇原创文章 · 获赞 864 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/Woo_home/article/details/101999915