Comparing the enum constants in thymeleaf

前端 未结 10 2297
自闭症患者
自闭症患者 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条回答
  •  渐次进展
    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.

提交回复
热议问题