본문 바로가기
Thymeleaf

[Thymeleaf] 셀렉트 박스에서의 th:selected 사용법

by 무사뎀벨레 2022. 5. 10.

 

Thymeleaf 템플릿을 사용하여 select box의 option항목을 나열하는 와중에,
기존의 저장된 값이 있으면 해당 옵션 속성에 selected를 추가하는 과정이 있었습니다.

 

 

 

 

기존 방법


처음에 아래와 같이 작업을 진행 하였습니다.

서버단에서 받아오는 result값의 joinSize1부터 10까지 반복하는 num값과 비교해, 동일하면 selected 속성을 추가하려는 의도였습니다. 하지만, 의도대로 되지 않았습니다.

<select class="form-control col-lg-2 required">
    <th:block th:each="num : ${#numbers.sequence(1,10)}">
        <option th:value="${num}" th:text="${num}" th:if="${result.joinSize eq num ? 'selected' : ''}">
        </option>
    </th:block>
</select>

 

 

 

 

th:selected 사용


이후 검색을 통해 타임리프는 th:selected를 사용해 selected 속성을 추가한다는 점을 알았습니다.

<select class="form-control col-lg-2 required">
	<th:block th:each="num : ${#numbers.sequence(1,10)}">
		<option th:value="${num}" th:text="${num}" th:selected="${num} == ${result.joinSize}">
        </option>
	</th:block>
</select>

 

또한 th:selected를 통해 비교를 할 경우 th:selected="${num} == ${result.joinSize}"와 같이
${비교대상 1 == 비교대상 2}가 아닌 ${비교대상 1} == ${비교대상 2}와 같은 형식으로 비교를 진행하면 됩니다.

반응형

댓글