타임리프에서 enum 타입을 이용해서 무언가 값을 처리하고 싶다. 예를 들면 어떤 상품의 카테고리와 같은.. 이런 경우에 enum을 처리할 수 있는데 방법은 두 가지가 있다.
enum이 아래와 같이 있다고 가정해보자.
public enum ItemType {
BOOK("도서"),
FOOD("음식"),
ETC("기타");
private final String description;
ItemType(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
앞에서 활용한 스프링 기능을 이용해 아래와 같이 처리해서 enum의 값들을 반환해서 모델에 담아 넘겨준다.
@ModelAttribute("itemTypes")
public ItemType[] itemTypes() {
return ItemType.values();
}
타임리프를 이용하면 html 파일에서 직접 접근하도록 코드를 작성할 수 있다. 하지만 이를 이용하면 html 코드에 불필요한 패키지 명 등이 들어가므로 가독성에 좋지 한다. (물론 렌더링 후에는 보이지 않지만)
더불어 패키지를 이동하거나 하는 등의 이슈가 생겼을 때 일일히 수정해주어야 하는 번거로움이 있기 때문에 알고만 있자 !
<div th:each="type : ${T(hello.itemservice.domain.item.ItemType).values()}">
<!-- radio button -->
<div>
<div>상품 종류</div>
<div th:each="type : ${itemTypes}" class="form-check form-check-inline">
<input type="radio" th:field="*{itemType}" th:value="${type.name()}" class="form-check-input" required>
<label th:for="${#ids.prev('itemType')}" th:text="${type.description}" class="form-check-label">BOOK</label>
</div>
</div>
enum의 경우, 선언한 description을 활용하고 싶으면 반드시 enum에서 getter를 만들어두어야 한다. 그래야만 th:text="${type.description}"
이 부분이 동작하게 된다.
getter를 정상적으로 만들어두어야만 th:text="${type.description}"
또는 th:text="${type.getDescription()}"
을 입력하면 동작한다.