1. Introduction
In this article, we will show methods to dynamically add and remove CSS class in Thymeleaf templates. This functionality is commonly used by developers, everyone face that problem at least once in his/her career.
If you need some more information about how to integrate Thymeleaf with Spring Boot application, or how to use conditions, please check below links:
Spring Boot with Thymeleaf
Using conditions in Thymeleaf
How to use if-else in Thymeleaf with Spring Boot?
2. Using th:classappend
attribute
Thymeleaf comes with th:classappend
attribute that was created for adding a style class to an element without overwriting the existing defined classes.
The following example shows how to use it conditionally:
If ${condition}
is true the rendered website will look like the following:
when ${condition}
is false the result will be:
Thymeleaf gives the ability to provide an inline condition without else command, that will looks like the following:
In this case when ${condition}
is false, null will be returned and no class will be appended to the attribute.
3. Conclusion
This article showcased the easy way to conditionally add/remove a class to any element in Thymeleaf. Special attribute th:classappend
seems to be the best solution, because it appends class not replace existing ones.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}