1. Introduction
Thymeleaf is a featured template engine for processing HTML documents widely used by web developers in Spring Boot applications. The engine uses simple XML attributes that cover almost all HTML5 attributes and adds many more. In this short article, we are going to present how to conditionally check checkboxes in Thymeleaf forms.
2. Using th:checked
attribute
Thymeleaf attributes accept not only simple primitive variables but any expression that could be evaluated by the engine. We can dynamically control what will be rendered on the output website.
th:checked
attribute is a Thymeleaf representation of checked
attribute in HTML documents used for checkboxes. It accepts Boolean variables or methods that return Boolean values.
To present how th:checked
attribute works we prepare a simple application with the following controller class:
In our template we will use flag variable and customer.active attribute to set initial value of checboxes on the form:
3. Conclusion
In this article, we presented how to conditionally checked checkboxes in Thymeleaf templates. Thymeleaf engine evaluates the expression in the dedicated attributes so we can easily control components using Java objects.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}