https://programmingsummaries.tistory.com/381?category=485241 

 

[JavaScript] 예제로 확인하는 handlebars.js 사용 방법

들어가며 최근 서버 사이드 템플릿 엔진 변경에 대한 논의가 있어서 주요 템플릿 엔진에 대해서 살펴보고 정리할 기회가 생겼다. 그 중에서 handlebars.js(이하 핸들바)  사용법에 대해 정리한 내용

programmingsummaries.tistory.com

여기 설명 잘 되어 있는데,

 

<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>{{id23}}</td> 
            
            {{!-- 사용자 정의 헬퍼인 email에 id를 인자로 넘긴다 --}}
            <td><a href="mailto:{{email id23}}">{{email id23}}</a></td> 
        </tr> 
        {{/users}} 
    </tbody> 
</table>
</script>

인자와 파라미터 구분이 애매해서 id를 x로 바꾼게 더 이해가 잘되어서.

//핸들바 템플릿 가져오기
var source = $("#entry-template").html(); 

//핸들바 템플릿 컴파일
var template = Handlebars.compile(source); 

//핸들바 템플릿에 바인딩할 데이터
var data = {
     users: [
            { name: "홍길동1", id23: "aaa1" },
            { name: "홍길동2", id23: "aaa2" },
            { name: "홍길동3", id23: "aaa3" },
            { name: "홍길동4", id23: "aaa4" },
            { name: "홍길동5", id23: "aaa5" },
            { name: "길동아", id23: "ffdsf"}
        ]
}; 

//커스텀 헬퍼 등록 (id를 인자로 받아서 전체 이메일 주소를 반환)
Handlebars.registerHelper('email', x => {
  return x + "@daum.net";
});

//핸들바 템플릿에 데이터를 바인딩해서 HTML 생성
var html = template(data);

//생성된 HTML을 DOM에 주입
$('body').append(html);

 

해당 필자 깃헙도 팔로우 했다. 웹 FE 쪽에서는 어떤 프레임웍으로 가는지 궁금해서.

+ Recent posts