SpringBoot集成Thymeleaf模板引擎

本文介绍了Thymeleaf模板引擎的特点及如何在Spring Boot中集成Thymeleaf,并通过实例展示了Thymeleaf的基本使用方法,包括页面布局、数据绑定等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Thymeleaf模板布局

Thymeleaf是一个跟Velocity、FreeMarker类似的模板引擎。它拥有如下特点:

(1)自然模板,原型及页面。开箱即用。

(2)语法易懂,支持OGNL、SpringEL。

(3)遵循web标准

2.springBoot集成Thymeleaf

build.gradle添加对Thymeleaf的依赖


添加thymeleaf指定版本:

		
	// 自定义  Thymeleaf 和 Thymeleaf Layout Dialect 的版本
	ext['thymeleaf.version'] = '3.0.3.RELEASE'
	ext['thymeleaf-layout-dialect.version'] = '2.2.0'

ok,配置文件搞定了,接下来我们开始写代码。

3.Thymeleaf实战-前后台编码

(1)代码结构


(2)application.properties配置

# THYMELEAF 
spring.thymeleaf.encoding=UTF-8
# 热部署静态文件
spring.thymeleaf.cache=false
# 使用HTML5标准
spring.thymeleaf.mode=HTML5

(3)Thymeleaf前端页面

list.htm

区分:th:insert & th:replace & th:include

userModel是服务端返回前端的数据模型

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <title th:text="${userModel.title}">welcome</title>
</head>
<body>
<div th:replace="~{fragments/header :: header}">...</div>
<h3 th:text="${userModel.title}">Welcome to waylau.com</h3>
<div>
    <a href="/users/form.html">创建用户</a>
</div>
<table border="1">
    <thead>
    <tr>
        <td>ID</td>
        <td>Age</td>
        <td>Name</td>
    </tr>
    </thead>
    <tbody>
    <tr th:if="${userModel.userList.size()} eq 0">
        <td colspan="3">没有用户信息!!</td>
    </tr>
    <tr th:each="user : ${userModel.userList}">
        <td th:text="${user.id}">1</td>
        <td th:text="${user.age}">11</td>
        <td><a href="view.html" th:href="@{'/users/' + ${user.id}}"
               th:text="${user.name}">waylau</a></td>
    </tr>
    </tbody>
</table>
<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>

(4)后台编码

@RestController
@RequestMapping("/users")
public class UserController {
	
	@Autowired 
	private UserRepository userRepository;

	/**
	 * 从 用户存储库 获取用户列表
	 * @return
	 */
	private List<User> getUserlist() {
 		return userRepository.listUser();
	}

	/**
	 * 查询所用用户
	 * @return
	 */
	@GetMapping
	public ModelAndView list(Model model) {
		model.addAttribute("userList", getUserlist());
		model.addAttribute("title", "用户管理");
		return new ModelAndView("users/list", "userModel", model);
	}
 }

在日常使用Thymeleaf的开发过程中,大家可参考基本语法进行编码。

https://blog.youkuaiyun.com/zrk1000/article/details/72667478

https://www.thymeleaf.org/apidocs/thymeleaf/3.0.9.RELEASE/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值