Handlebars 예제 #2
가장 기본적인 사용자 정의 헬퍼
by Jaeha Ahn
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.2/handlebars.min.js"></script>
<script id="entry-template" type="text/x-handlebars-template">
<table>
<thead>
<th>이름</th>
<th>아이디</th>
<th>메일주소</th>
</thead>
<tbody>
{{#users}}
<tr>
<td>{{name}}</td>
<td>{{id}}</td>
{{!-- 사용자 정의 헬퍼인 email에 id를 인자로 넘긴다 --}}
<td><a href="mailto:{{email id}}">{{email id}}</a></td>
</tr>
{{/users}}
</tbody>
</table>
</script>
JavaScript
//핸들바 템플릿 가져오기
var source = $("#entry-template").html();
//핸들바 템플릿 컴파일
var template = Handlebars.compile(source);
//핸들바 템플릿에 바인딩할 데이터
var data = {
users: [
{ name: "홍길동1", id: "aaa1" },
{ name: "홍길동2", id: "aaa2" },
{ name: "홍길동3", id: "aaa3" },
{ name: "홍길동4", id: "aaa4" },
{ name: "홍길동5", id: "aaa5" }
]
};
//커스텀 헬퍼 등록 (id를 인자로 받아서 전체 이메일 주소를 반환)
Handlebars.registerHelper('email', function (id) {
return id + "@daum.net";
});
//핸들바 템플릿에 데이터를 바인딩해서 HTML 생성
var html = template(data);
//생성된 HTML을 DOM에 주입
$('body').append(html);