[themeleaf] foreach시 이전 아이템과 현재 아이템 비교하기

2021. 10. 14. 11:30전자정부 업글/Thymeleaf 적용기

반응형

위와 같이 테이블에 항목을 출력한다고 하자!

'서비스 구분'항목이 반복되면서 출력하다보니 가독성이 떨어진다.

마치 트리처럼 보여지게 할순 없을까?(아래 참고)

그렇게 되려면 이전값과 현재값을 비교해야한다.

하지만 우린 foreach에서 itemList 객체에 item만 추출해서 써봤지 itemList를 인덱스로 접근할 생각은 못해봤다!

그럼 방법이 없을까? 하고 찾아보니 있더라! javascript map 사용하는것 처럼

itemList[index] 요로코롬 사용해주면 접근가능하다!

 

<table>
	<colgroup>
		<col style="width: 33%;">
		<col style="width: 33%">
		<col style="width: 33%">
	</colgroup>
	<thead>
		<tr>
		<th>서비스 구분</th>
		<th>서비스 명</th>
		<th>최종 상태</th>						
		</tr>
	</thead>
	<tbody>
		<tr th:each="item , status : ${itemList}">
			<td th:with="isDuplicated=${status.index > 0 && itemList[status.index-1].servDiv == itemList[status.index].servDiv}">
				[[${isDuplicated? '&nbsp;':item.servDiv}]]
			</td>
			<td>[[${item.servNm}]]</td>
			<td>[[${item.progress == 'ACCEPT'? '사용중':'-'}]]</td>
		</tr>
	</tbody>
</table>

소스에 대해 설명을 하자면, 

th:with="isDuplicated=${status.index > 0 && itemList[status.index-1].servDiv == itemList[status.index].servDiv}"

=> isDuplicated 변수에 이전값과 현재값을 비교하여 중복여부를 체크하고 있다. 물론 index가 0 보다 큰녀석일때 이전값이 있을것이다.

혹시나 콜렉션 객체에 index로 접근할일 있으면 이렇게 활용하라!

반응형