[Spring Thymeleaf] Enum 타입 메시지, 국제화 적용

dondonee·2023년 11월 3일
0

Enum 타입 메시지, 국제화 적용

문제


투두리스트 타임리프 템플릿 파일에 메시지를 적용하고 있었는데 문제가 생겼다.

나는 Task(할 일)의 Priority(우선순위) 항목을 Enum 타입으로 만들었다. DB에는 대문자 영어(HIGH, MEDIUM, LOW)로 저장하고, description 필드를 사용해 사용자에게는 한국어(높음, 보통, 낮음)로 보여줬었다.

그런데 다국어 기능을 추가하려고 보니 이 경우에는 일반적인 th:text=”#{…}” 문법으로는 국제화 적용이 불가능했다.


public enum Priority {

    HIGH("높음"), MEDIUM("보통"), LOW("낮음");

    private final String description;
		...
}
<p th:text="#{label.priority}">우선순위</p>
<th:block th:each="pr : ${priorities}">
    <input type="radio" th:field="*{priority}" th:value="${pr.name()}">
    <label th:for="${#ids.prev('priority')}" th:text="${pr.getDescription()}"></label>
</th:block>
  • [할 일 등록] 폼의 코드이다. Enum 타입인 Priority의 열거 상수들을 priorities 리스트에 저장하고, 이것을 View가 받아서 반복문을 통해 radio 버튼을 표시한다.

챗지피티에게 물어보니 영 이상한 대답을 해 줬는데… 다행히 검색해보니 영한님 스프링 강의를 듣는 분 중에 비슷한 질문을 하신 분이 계셔서 그것을 참고했다.


해결

  1. Enum 클래스 description 필드에 메시키 키를 적용한다.

    public enum Priority {
    
     HIGH("label.priority.HIGH"), MEDIUM("label.priority.MEDIUM"), LOW("label.priority.LOW");
    
     private final String description;
    ...
    }
  2. 언어별 메시지 관리 파일에 메시지 내용을 작성한다.

    label.priority=Priority
    label.priority.HIGH=High
    label.priority.MEDIUM=Medium
    label.priority.LOW=Low
  3. 템플릿에서 th:text=”#{${key}}” 문법을 사용해 출력한다. 끝!

    <p th:text="#{label.priority}">우선순위</p>
    <th:block th:each="pr : ${priorities}">
        <input type="radio" th:field="*{priority}" th:value="${pr.name()}">
        <label th:for="${#ids.prev('priority')}" th:text="#{${pr.getDescription()}}"></label>
    </th:block>

0개의 댓글