Web Front-end
HTML Tutorial
Using Boolean attributes to implement conditional display of containers in Spring Boot Thymeleaf
Using Boolean attributes to implement conditional display of containers in Spring Boot Thymeleaf

When building dynamic web applications, it is a common requirement to control the display and hiding of front-end UI elements based on back-end logic. Spring Boot combines with the Thymeleaf template engine to provide powerful conditional rendering capabilities. This article will delve into how to correctly pass Boolean type attributes in Spring Boot controllers and use the `th:if` directive in Thymeleaf templates to implement conditional display of containers.
Understanding Thymeleaf’s conditional rendering
Thymeleaf's th:if attribute is used to conditionally render HTML elements. It accepts a boolean expression as parameter. When the expression evaluates to true, the element and its contents are rendered; when it evaluates to false, the element is not rendered into the final HTML output.
In the original question, the developer tried to control the display by passing the string "true", for example:
String showContent = "true";
modelandview.addObject("showContent", showContent);
and use in Thymeleaf template:
<div th:if="${showContent}=='true'" id="container-two">
<!-- ... content... -->
</div>
While this approach appears to work on the surface because it performs a string comparison, it is not Thymeleaf's best practice for handling boolean values and can lead to potential type mismatches or logic errors. Thymeleaf's expression languages (such as OGNL or Spring EL) can directly evaluate values of Boolean type.
Correctly passing boolean properties
In order to take full advantage of Thymeleaf's features and ensure the robustness of the code, we should pass a native boolean value directly from the Spring Boot controller instead of its string representation.
Spring Boot controller side
In a Spring Boot controller, when you need to pass a Boolean state to the view, you should use Java's boolean type directly.
Example using ModelAndView:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MyController {
@GetMapping("/myPage")
public ModelAndView showMyPage() {
ModelAndView modelAndView = new ModelAndView("myTemplate"); // Assume the template is named myTemplate.html
// Correct approach: directly pass the Boolean type boolean showContainerTwo = true;
modelAndView.addObject("showContainerTwo", showContainerTwo);
// Example: Pass other data modelAndView.addObject("vmnameshowlinux", "LinuxVM-01");
modelAndView.addObject("ipaddresslinux", "192.168.1.100");
modelAndView.addObject("vmnameshowwin", "WindowsVM-01");
modelAndView.addObject("ipaddresswin", "192.168.1.101");
return modelAndView;
}
}
Example using Model (more recommended way):
If your controller method returns a string (view name) directly, you can add properties through the Model interface.
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MyController {
@GetMapping("/myPageWithModel")
public String showMyPageWithModel(Model model) {
// Correct approach: directly pass the Boolean type boolean showContainerTwo = true;
model.addAttribute("showContainerTwo", showContainerTwo);
// Example: Pass other data model.addAttribute("vmnameshowlinux", "LinuxVM-01");
model.addAttribute("ipaddresslinux", "192.168.1.100");
model.addAttribute("vmnameshowwin", "WindowsVM-01");
model.addAttribute("ipaddresswin", "192.168.1.101");
return "myTemplate"; // Return template name}
}
Thymeleaf template side
In Thymeleaf templates, when the attribute is a Boolean type, it can be directly used as a parameter of th:if without string comparison.
<title>VM Details</title>
<style>
.container-two {
border: 1px solid #ccc;
padding: 15px;
margin-top: 20px;
}
.container-linux, .container-windows {
border: 1px solid #eee;
padding: 10px;
margin-bottom: 10px;
display: flex;
align-items: center;
gap: 10px;
}
.col {
width: 50px;
height: auto;
}
</style>
<!-- Use th:if to directly determine the Boolean value -->
<div th:if="${showContainerTwo}" id="container-two" class="container-two">
<h3>VM Information</h3>
<div class="container-linux">
<div>
<img class="col lazy" src="/static/imghw/default1.png" data-src="@{/images/linux.png}" th: alt="Linux Icon"><br>
<label>VM Name is</label>
<a style="font-weight: bold;" th:text="${vmnameshowlinux}"></a><br>
<label>VM IpAddress is</label>
<a style="font-weight: bold;" th:text="${ipaddresslinux}"></a>
</div>
<a th:href="@{/launchconsole}" class="btn btn-success">Launch RDP</a>
</div>
<div class="container-windows">
<div>
<img class="col lazy" src="/static/imghw/default1.png" data-src="@{/images/windows.png}" th: alt="Windows Icon"><br>
<label>VM Name is</label>
<a style="font-weight: bold;" th:text="${vmnameshowwin}"></a><br>
<label>VM IpAddress is</label>
<a style="font-weight: bold;" th:text="${ipaddresswin}"></a>
</div>
<a th:href="@{/launchconsole}" class="btn btn-success">Launch RDP</a>
</div>
</div>
<!-- If showContainerTwo is false, other content can be displayed here, such as: -->
<div th:unless="${showContainerTwo}">
<p>No VM information to display at this time.</p>
</div>
In the above Thymeleaf code, th:if="${showContainerTwo}" will directly check the Boolean value of the showContainerTwo variable. If showContainerTwo is true, the entire div element with id="container-two" will be rendered; if it is false, the div will not appear in the final HTML.
Things to note and best practices
- Type matching: Always ensure that the data type passed from the backend is consistent with the type expected by the frontend. For conditional rendering, passing a boolean value is the most straightforward and recommended way.
- Default: If a boolean property may not exist in the Model, Thymeleaf will evaluate it to false. This means that even if not set explicitly, th:if="${nonExistentBoolean}" will safely evaluate to false, thus hiding the element.
- th:unless: Thymeleaf also provides the th:unless attribute, which has the opposite effect of th:if. When the expression evaluates to false, the element is rendered. For example, th:unless="${showContainerTwo}" is equivalent to th:if="${!showContainerTwo}".
- Clear variable naming: Using descriptive variable names (such as showContainerTwo instead of simply showContent) can improve the readability of your code.
- Performance: th:if and th:unless are processed on the server side, and they determine which HTML fragments will be sent to the client, thereby reducing unnecessary DOM rendering and network transmission.
Summarize
The key to implementing conditional display of containers in a Spring Boot Thymeleaf project is to correctly pass the Boolean type attribute from the controller and evaluate the Boolean value directly using the th:if directive in the Thymeleaf template. This method is not only concise and easy to understand, but also conforms to Thymeleaf's design philosophy and can effectively improve development efficiency and application performance. By following these best practices, developers can build more robust and responsive web interfaces.
The above is the detailed content of Using Boolean attributes to implement conditional display of containers in Spring Boot Thymeleaf. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
How to correctly migrate jQuery's drag and drop events to native JavaScript
Mar 06, 2026 pm 05:15 PM
This article explains in detail the key pitfalls when migrating jQuery drag-and-drop logic (such as dragover/dragleave) to Vanilla JS - especially the problem of misuse of e.originalEvent causing dataTransfer failure, and provides directly runnable fixes and best practices.
How to make the images in a div fill with no margins while retaining the inner margins of the text
Mar 07, 2026 pm 10:54 PM
This article explains how to keep the overall padding of the container so that the internal images are displayed close to the edge of the container, while the text content still maintains normal padding - the core is to separate the style scope and achieve precise layout through positioning and box model control.
Solve the problem of unexpected offset of Flex container due to the font size change of the first child element
Mar 09, 2026 pm 08:15 PM
When the first child element of a Flex container dynamically adjusts the font-size, the container will be vertically offset along the inline baseline; while a normal block-level container will change in height due to the linkage between line height and font measurement. The root cause lies in the baseline alignment mechanism of the Flex container. By default, the baseline of the first child is the container baseline. This can be completely solved through vertical-align: top or explicit baseline control.
Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart)
Mar 12, 2026 pm 08:51 PM
This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.
A complete guide to using the keyboard to control the smooth movement of HTML elements
Mar 13, 2026 pm 10:18 PM
This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.
How to dynamically pass HTML form data to analytics.track() method
Mar 13, 2026 pm 10:57 PM
This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.
How to properly override default styles and implement custom CSS layouts in Divi theme builder
Mar 14, 2026 am 12:00 AM
This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.
How to optimize Lighthouse image scoring while maintaining high image quality
Mar 11, 2026 pm 09:39 PM
This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.





