I have an enum, Constants:
enum Constants { ONE,TWO,THREE; } How can I compare the enum Constants in Thymeleaf.
Thanks.
I have an enum, Constants:
enum Constants { ONE,TWO,THREE; } How can I compare the enum Constants in Thymeleaf.
Thanks.
To compare with an enum constant, use the following code:
th:if="${day == T(my.package.MyEnum).MONDAY}" One more way:
th:if="${constant.name() == 'ONE'}" It's shorter but makes compare with string representation, can cause problem while refactoring.
@Nick answer has a small syntax error, it's missing a final brace. It should be
th:if="${day == T(my.package.MyEnum).MONDAY}" th:if="${#strings.toString(someObject.constantEnumString) == 'ONE'}"> Try this :
th:if="${ day.toString() == 'MONDAY'}" Another option is using the method name() of the enum in a switch. An example would be:
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.
If you don't want to convert your Enum into a string in your object you can do it like this:
th:if="${#strings.defaultString(someObject.myConstant, 'DEFAULT_VALUE') == 'ONE'}" I prefere use wrapper around the enum.
public class ConstantsWrapper { public static final instance = new ConstantsWrapper(); public Constants getONE() { return Constants.ONE } public Constants getTWO() { return Constants.TWO } public Constants getTHREE() { return Constants.THREE } } Next step is adding new instance of Wrapper into models
models.add("constantsWrapper", ConstantsWrapper.instance); Now you have type safe access in thymeleaf template to the each value of Constants.
th:if="${value == constantsWrapper.getONE()}" I know that this solutions needs to write more source code and create one instnace. Advantage is more type safe than call T() and write full qualified name directly into template. With this solution you can refactor without testing your templates.
I tend to add isXXX() methods to my enums:
enum Constants { ONE,TWO,THREE; public boolean isOne() { return this == ONE; } public boolean isTwo() { return this == TWO; } public boolean isThree() { return this == THREE; } } Then, if value is an instance of your enum, you can use th:if="${value.one}".