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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
 
<script src="./lib/jquery/1.9.1/jquery.min.js"></script>
<script src="./lib/handlebars/4.0.10/handlebars.js"></script>
</head>
<body>
 
    <ul id="testData">
    </ul>
 
    <script id="template" type="text/x-handlebars-template">
        {{#each members}}  
                 <li>
                    {{@index}} :
                    {{name}}
                    {{fn_dateTest regdate}}
                </li>
        {{/each}}
    </script>
 
    <script type="text/javascript">
        
        // 헬퍼함수 만들기
        // 헬퍼함수는 Handlebars.registerHelper()를 사용해서 등록할 수 있다.
        // 헬퍼함수는 스크립트 상단에 선언하자 (호이스팅)
        // Handlebars.registerHelper("선언함수명", function(args..., option){ ... }
        // args 매개변수 인자보다.. 그냥 this.변수명 으로 접근은 편하다.
 
        Handlebars.registerHelper("fn_dateTest", function(regdate, option) {
 
            console.log(this); // this == jQuery에서 el과 같다. (반복문에서 현재 컨텐스트)
            console.log(this.regdate);
            console.log(regdate);
            console.log(option);
 
            var dateObj = new Date(regdate);
            var year = dateObj.getFullYear();
            var month = dateObj.getMonth() + 1;
            var date = dateObj.getDate();
            return year + "-" + month + "-" + date;  
        });
 
        var testData = {
            members : [ 
                { name : '이소룡', regdate: 1496893345000}, 
                { name : '김양용', regdate: 1496893341000}, 
                { name : '전땡감', regdate: 1496893330000}, 
                { name : '김조조', regdate: 1496893310000}, 
                { name : '김나라', regdate: 1496893380000} 
            ]
        }
 
        var template = Handlebars.compile($('#template').html());
        var html = template(testData);
        $("#testData").append(html);
 
    </script>
</body>
</html>


반응형
Posted by 힘없는염소