Comparing the enum constants in thymeleaf

前端 未结 10 2048
自闭症患者
自闭症患者 2021-02-02 06:25

I have an enum, Constants:

enum Constants {
    ONE,TWO,THREE;
}

How can I compare the enum Constants in Thymeleaf.

Thank

相关标签:
10条回答
  • To compare with an enum constant, use the following code:

    th:if="${day == T(my.package.MyEnum).MONDAY}"
    
    0 讨论(0)
  • 2021-02-02 07:02

    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'}"
    
    0 讨论(0)
  • 2021-02-02 07:04

    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.

    0 讨论(0)
  • 2021-02-02 07:06

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

    th:if="${day == T(my.package.MyEnum).MONDAY}"
    
    0 讨论(0)
  • 2021-02-02 07:06

    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.

    0 讨论(0)
  • 2021-02-02 07:08

    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}".

    0 讨论(0)
提交回复
热议问题