Thymleaf switch statement with multiple case
The failure is due to the fact that you don't have a valid expression in the first case. Specifically,
'COMPLETE','INVALID'
is not a valid expression. I suspect that what you are trying to do is include the div if the status is COMPLETE or INVALID. Unfortunately, I believe you will have to duplicate the markup for those conditions individually. Let me suggest the following markup:
<!-- th:block rather than unneeded div -->
<th:block th:switch="${status.value}">
<div th:case="'COMPLETE'">
<!-- print object is not active -->
</div>
<div th:case="'INVALID'">
<!-- print object is not active -->
</div>
<div th:case="'NEW'">
<!-- print object is new and active -->
</div>
</th:block>
Alternatively you could resort to th:if which might actually work better in this case:
<div th:if="${status.value} eq 'COMPLETE' or ${status.value} eq 'INVALID'">
<!-- print object is not active -->
</div>
<div th:if="${status.value} eq 'NEW'">
<!-- print object is new and active -->
</div>
Or even more simply:
<div th:unless="${status.value} eq 'NEW'">
<!-- print object is not active -->
</div>
<div th:if="${status.value} eq 'NEW'">
<!-- print object is new and active -->
</div>
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.
<div th:switch="${#strings.toString(datafile.status)}">
<td th:case="'SUCCESS'" class="table-success">SUCCESS</td>
<td th:case="'FAILED'" class="table-danger">FAILED</td>
<!-- default case -->
<td th:case="*" th:text="${#strings.toString(datafile.status)}" class="table-secondary">xxx</td>
</div>
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
:
<tr th:class="${datafile.bootstrapTableRowClassForStatus}">
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.