Comparing the enum constants in thymeleaf

I have an enum, Constants:

enum Constants {
    ONE,TWO,THREE;
}

How can I compare the enum Constants in Thymeleaf.

Thanks.


Solution 1:

To compare with an enum constant, use the following code:

th:if="${day == T(my.package.MyEnum).MONDAY}"

Solution 2:

One more way:

th:if="${constant.name() == 'ONE'}"

It's shorter but makes compare with string representation, can cause problem while refactoring.

Solution 3:

@Nick answer has a small syntax error, it's missing a final brace. It should be

th:if="${day == T(my.package.MyEnum).MONDAY}"

Solution 4:

Another option is using the method name() of the enum in a switch. An example would be:

  <th:block th:switch="${imageType.name()}>
     <span th:case="'ONE'"></span>
     <span th:case="'TWO'"></span>
     <span th:case="'THREE'"></span>
  </th:block>

It is similar to a Java Switch swith ENUM instead of other answers like ${day == T(my.package.MyEnum).MONDAY} or ${#strings.toString(someObject.constantEnumString) == 'ONE'} which looks very strange.