diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/conditionalclasses/ConditionalClassesController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/conditionalclasses/ConditionalClassesController.java new file mode 100644 index 0000000000..712f036ed1 --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/conditionalclasses/ConditionalClassesController.java @@ -0,0 +1,15 @@ +package com.baeldung.thymeleaf.conditionalclasses; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class ConditionalClassesController { + + @GetMapping("/conditional-classes") + public String getConditionalClassesPage( Model model) { + model.addAttribute("condition", true); + return "conditionalclasses/conditionalclasses"; + } +} diff --git a/spring-thymeleaf-3/src/main/resources/templates/conditionalclasses/conditionalclasses.html b/spring-thymeleaf-3/src/main/resources/templates/conditionalclasses/conditionalclasses.html new file mode 100644 index 0000000000..8383abda29 --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/templates/conditionalclasses/conditionalclasses.html @@ -0,0 +1,42 @@ + + + + + Conditional CSS Classes in Thymeleaf + + +

The Goal

+

+ + I have two classes: "base" and either "condition-true" or "condition-false" depending on a server-side condition. + +

+

Using th:if

+

+ + This HTML is duplicated. We probably want a better solution. + + + This HTML is duplicated. We probably want a better solution. + +

+

Using th:attr

+

+ + This HTML is consolidated, which is good, but the Thymeleaf attribute still has some redundancy in it. + +

+

Using th:class

+

+ + The base CSS class still has to be appended with String concatenation. We can do a little bit better. + +

+

Using th:classappend

+

+ + This HTML is consolidated, and the conditional class is appended separately from the static base class. + +

+ + \ No newline at end of file