在Spring Boot与Thymeleaf的项目中,我们经常需要根据后端返回的布尔值来决定某个容器是否在页面上渲染。Thymeleaf提供了一系列布尔属性,让这种条件显示变得非常简单且直观。

什么是Thymeleaf布尔属性
布尔属性是指其值只关心真假的表达式属性,最常用的包括th:if和th:unless。当表达式结果为真时,th:if所在的标签及其内容会被渲染;th:unless则正好相反。
后端控制器如何传递布尔值
在Spring Boot的Controller中,我们可以把一个布尔变量放入Model,供前端页面读取。
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {
@GetMapping("/home")
public String home(Model model) {
// 根据业务逻辑判断是否显示公告容器
boolean showNotice = true;
model.addAttribute("showNotice", showNotice);
return "home";
}
}
页面中利用布尔属性控制容器
在Thymeleaf模板中,使用th:if来条件显示容器。只有当showNotice为true时,下面的div才会输出到HTML中。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<div th:if="${showNotice}" class="notice-box">
<p>系统维护通知:今晚凌晨将进行升级。</p>
</div>
<div th:unless="${showNotice}">
<p>当前没有新通知。</p>
</div>
</body>
</html>
使用注意事项
- th:if表达式为false时,元素本身及其子元素都不会生成在最终页面中,而不是隐藏。
- 如果需要用非布尔类型判断,Thymeleaf会把null、空字符串、0等视为假值。
- 不要将布尔属性与HTML原生disabled等布尔属性混淆,后者是标签自身的语法。
小结
通过Spring Boot后台传递布尔变量,再配合Thymeleaf的th:if与th:unless,可以优雅地实现容器的条件显示,减少前端脚本的耦合,提升代码可读性。
Spring_BootThymeleaf布尔属性修改时间:2026-07-26 13:00:15