2023-04-21 19:41:24

jsrender에서 for문을 사용할 때 슬라이싱 범위를 지정하는 방법에 대해 알아보겠습니다. 

 

for 문 시작 부분에 start=시작 인덱스, end=종료 인덱스+1 을 넣어주시면 됩니다. 

 

{{for people start=0 end=3}}
{{:name}}
{{/for}}

 

start=0 end=3이면, 인덱스 0, 1, 2까지의 데이터가 포함됩니다. 

 

전체 코드는 다음과 같습니다. 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://www.jsviews.com/download/jsviews.min.js"></script>

    <title>Document</title>
</head>
<body>
    <div id="result"></div>

    <script id="theTmpl" type="text/x-jsrender">
        {{for people start=0 end=3}}
        {{:name}}
        {{/for}}
    </script>
  

    <script>
        var data = {
            people: [
                {name: '심교훈', age: 18}, // index 0
                {name: '문태호', age: 19}, // index 1
                {name: '황병일', age: 20}, // index 2
                {name: '정하연', age: 21}, // index 3
                {name: '이정기', age: 22}, // index 4
            ]
        };

        var template = $.templates("#theTmpl");
        var htmlOutput = template.render(data);
        $("#result").html(htmlOutput);

    </script>
</body>
</html>

 

이 html 문서를 브라우저에서 열어보면 다음과 같이 보여집니다. 

 

 

start=2 end=4 로 바꾸면 다음과 같이 렌더링됩니다.

 

 

참고자료

[1] https://www.jsviews.com/#fortag