지식

[Thymeleaf]타임리프 자바스크립트 반복문 (thymeleaf javascript loop)

애앨리 2020. 9. 9. 11:39

스프링 부트를 사용 하면서 view 페이지 템플릿으로 타임리프를 많이 사용하는데
HTML LOOP 문 예제는 많으나 스크립트에서 LOOP도는 방법이 거의 없어서 남겨본다.

방식은 기존 방식과 동일한데 약간 다름(?) 

가타부타 부가 설명 보다는 소스를 보는게 빠르니


HTML block LOOP

1
2
3
4
5
6
7
8
9
10
11
<th:block th:each="ordInfo, status : ${orderDetailList}">
<tr class="txtC"> 
    <td>
        <a th:href="#">
            <th:block th:if="${ordInfo.Type == 'A'}">
                <img th:src="${ordInfo.goodsImgPath1}"/>
            </th:block>
        </a>
    </td
</tr>
</th:block>
cs


Javascript Loop

1
2
3
4
5
6
7
8
9
10
11
    <script th:inline="javascript">
        let gaOrderArrayArg = new Array();
        let gaOrderGoodsinfo = new Object();
        /*[# th:each="order : ${orderDetailList}"]*/
        gaOrderGoodsinfo.id =  /*[[${order.goodsCd}]]*/;
        gaOrderGoodsinfo.price =  /*[[${order.benefitPrice}]]*/;
        gaOrderGoodsinfo.quantity =  /*[[${order.ordQty}]]*/;
        gaOrderArrayArg.push(gaOrderGoodsinfo);
        /*[/]*/
 
    </script>
cs


Javascript 변수로 받아서 처리하는 Loop

1
2
3
4
5
6
7
8
9
10
11
<script>
    let orderDetailList = [[${orderDetailList}]];
    let gaOrderGoodsinfo = new Object();
    
    orderDetailList.forEach(function(item){
        gaOrderGoodsinfo.id = item.goodsCd
        gaOrderGoodsinfo.price = item.benefitPrice
        gaOrderGoodsinfo.quantity = item.ordQty
        gaOrderArrayArg.push(gaOrderGoodsinfo);
    });
</script>
cs

 

추가 2021.03.09

javascript 에

<th:block th:if ~~ 처럼 사용하기>

</th:block>

1
2
3
4
5
/*[# th:if="${custInfo != null && custInfo != ''}"]*/
 
    var custId = $('#joinForm input[name=custId]').val();
 
/*[/]*/
cs