In Short
I want to have switch statement in thymeleaf with logic once written to multiple case statements.
In detail
I
I hit the same issue today, where the object used in my th:switch
is a Java enum. I eventually figured out that this was a Java equals() versus == issue. In the th:switch
I have an enum object, but in my th:case
I have a String object. I solved it by using a Thymeleaf string function to convert the enum object to a string, and then everything works.
SUCCESS
FAILED
xxx
In my example above I'm using the switch to conditionally apply a Bootstrap style to a table cell.
An alternate solution is to perform the logic in Java code and expose the output value as an object property, then just reference that property in the Thymeleaf template. Something like this:
public String getBootstrapTableRowClassForStatus() {
Objects.requireNonNull(status);
switch (status) {
case SUCCESS:
return "table-success";
case FAILED:
return "table-danger";
case PROCESSING:
return "table-info";
default:
return "table-secondary";
}
}
and then I use Thymeleaf th:class
:
On my page, this will apply a Bootstrap color style to my table row based on the value of my Status enum in the Java object.
- 热议问题