Thymleaf switch statement with multiple case

Faraj Farook picture Faraj Farook · Apr 15, 2015 · Viewed 35.2k times · Source

In Short

I want to have switch statement in thymeleaf with logic once written to multiple case statements.

In detail

I want to implement this in the thymeleaf

switch(status.value){
  case 'COMPLETE':
  case 'INVALID':
     //print exam is not active
     break;
  case 'NEW':
     //print exam is new and active
     break;
}

My current thymleaf code which fails with runtime error

 <div th:switch="${status.value}">
      <div th:case="'COMPLETE','INVALID'">
         <!-- print object is not active -->
      </div>
      <div th:case="NEW'">
         <!-- print object is new and active -->
      </div>
 </div>                             

But the above code fails with error

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "'COMPLETE','INVALID'"...

Note: I know the reason for this above error message. All I need is to know a way to implement switch with multiple cases for a single output

Answer

pens-fan-69 picture pens-fan-69 · Apr 15, 2015

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>