티스토리 뷰

반응형

 

 

 



 

 

 

SpringBootthymeleaf

 

 

통계 집계한 데이터를 조회하여 table 에 그려주는 과정에서

중간중간마다 데이터 백분율을 작성해 주고 싶었다.

 

 

thymeleaf each 를 사용해서 조회한 데이터를 아래와 같이 그렸다.

 

<th:block th:each="data : ${tableData}">
  <tr>
	<td th:text="${data.type}"></td>
	<td th:text="${data.m01}"></td>
	<td th:text="${data.m02}"></td>
	<td th:text="${data.m03}"></td>
	<td th:text="${data.m04}"></td>
	<td th:text="${data.m05}"></td>
	<td th:text="${data.m06}"></td>
	<td th:text="${data.m07}"></td>
	<td th:text="${data.m08}"></td>
	<td th:text="${data.m09}"></td>
	<td th:text="${data.m10}"></td>
	<td th:text="${data.m11}"></td>
	<td th:text="${data.m12}"></td>
	<td th:text="${#numbers.formatInteger(data.rowSum, 1, 'COMMA')}"></td>
  </tr>
</th:block>

 

 

 

구분 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월 합계
접수                          
예약                          

 

 

 

실제로는 구분 앞에 대분류, 중분류가 더 있어서 위와 같은 형태가 여러개 그려지게 되는데

접수/예약/(예약율)/접수/예약/(예약율)/...

 

이렇게 중분류가 바뀌는 시점에 예약율 행을 추가해주고 싶었다.

 

처음엔 서비스단에서 데이터 가공을 해서 위코드 그대로 쓸까 했으나

thymeleaf 에서 해결 할 수 있지 않을까 싶어서 

타임리프 유틸들을 조합해서 해결해 보았다.

 

 

 

 

접수/예약 후에  (예약율) 행을 그려주면 되므로

짝수일때 수행하도록 하였다.

 

<th:block th:each="data : ${tableData}">
 ... 위에 코드
    <th:block th:if="${dataStat.even}">
      <tr>
        <td th:text="${'예약률'}"></td>
        <td th:with="rate=${data.m01 > 0 ? data.m01 * 1.0 / tableData[dataStat.index-1].m01 : 0}"
            th:text="${#numbers.formatPercent(rate,1,1)}">
        </td>

        ... 월 반복
        
      </tr>
    </th:block>      
</th:block>

 

 

구분 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월 합계
접수 1121                        
예약 903                        
예약율 80.6%                        

 

 

내가 생각한데로 테이블이 그려졌다.

 

dataStat 는  each 에서 리스트의 상태를 알 수 있는 상태변수인데

따로 명명하지 않으면 변수명 + Stat  로 사용할 수 있다.

 

상태에 대한 프로퍼티는 8가지있는데
나는 짝수번째를 찾기 위하  even 프로퍼티를 사용했고, 이전 값을 얻기 위해 index를 사용했다.

 

  • The current iteration index, starting with 0. This is the index property.
  • The current iteration index, starting with 1. This is the count property.
  • The total amount of elements in the iterated variable. This is the size property.
  • The iter variable for each iteration. This is the current property.
  • Whether the current iteration is even or odd. These are the even/odd boolean properties.
  • Whether the current iteration is the first one. This is the first boolean property.
  • Whether the current iteration is the last one. This is the last boolean property.

 

 


자세한 설명은 링크 참고!

 

 

Tutorial: Using Thymeleaf

1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a Java library. It is an XML/XHTML/HTML5 template engine able to apply a set of transformations to template files in order to display data and/or text produced by your applications. It is better s

www.thymeleaf.org


 

 

 

 

내가 백분율을 구하기 위해 사용한 코드는 아래와 같은데

가독성에 따른 여러 방법이 있을 듯 싶다.

<td th:with="rate=${data.m01 > 0 ? data.m01 * 1.0 / tableData[dataStat.index-1].m01 : 0}"
	th:text="${#numbers.formatPercent(rate,1,1)}"></td>

 

나는 th:with 를 사용하여 rate 라는 변수에 대상값이 0이 아닐경우 이전 값으로 나누고 

출력할때 소수점 한자리 퍼센트로 출력하라고 지정하였다.

 

 

 

 

 

 

여러가지 방법으로 작성할 수 있는데 
th:with 구문 사용안하고 바로 사용해도 되고

따로 값을 구해서 % 를 붙여주는 방식으로 해도 되고

<td th:text="${data.rowSum > 0 ? 
	#numbers.formatPercent(data.rowSum * 1.0 / tableData[dataStat.index-1].rowSum,1,1) 
    : 0 + '%'}"></td>
    

<td th:text="${data.rowSum > 0 ? 
#numbers.formatDecimal((data.rowSum * 1.0 / tableData[dataStat.index-1].rowSum) *100,1,1) +'%', 1) 
: 0 + '%'}"></td>

 

근데 결국 값을 구해서 #number.formatPercent()  유틸을 한번에 써주는게 더 효과적이긴 하다

% 문자열을 알아서 붙여주기 때문에?

 

 

 

 

 

 



 

 

참고블로그

 

 

타임리프 - 반복(th:each, index, ...)

반복 사용을 위해 데이터를 따로 넣어준다.th:each="user : ${users}"반복기능이다. 이건 잘 알고 있기 때문에 따로 설명은 패스th:each="user, userStat : ${users}"반복을 할때 그 상태까지 가져와준다.생략이

velog.io

 

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

위와 같이 테이블에 항목을 출력한다고 하자! '서비스 구분'항목이 반복되면서 출력하다보니 가독성이 떨어진다. 마치 트리처럼 보여지게 할순 없을까?(아래 참고) 그렇게 되려면 이전값과 현재

papababo.tistory.com

 

 

 

 

반응형
댓글
반응형
최근에 올라온 글
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Total
Today
Yesterday