2012-10-10 3 views
0

저는 현재 Handlebars를 사용하여 템플릿을 만드는 방법을 배우고 있으며 다음 2 개의 템플릿을 하나로 결합하고 각 스크립트가 올바른 값을 표시하도록 스크립트를 업데이트하는 방법에 대한 조언을 듣고 싶습니다.두 데이터 핸들러 템플릿을 결합하는 방법에 대한 조언?

템플릿

<script type="text/x-handlebars" id="infoTemp"> 
    {{#each films}} 
    <li> 
     <h2>{{title}}</h2> 
     <p>{{{description}}}</p>   
    </li> 
    {{/each}} 
</script> 
<script type="text/x-handlebars" id="additionalInfoTemp"> 
    {{#each films}} 
    <li> 
     <h1>{{id}}</h1> 
     <h2>{{title}}</h2> 
     <p>{{{description}}}</p> 
     <small>{{released}}</small>   
    </li> 
    {{/each}} 
</script> 

// Dummy data 
data = { 
    "films": [ 
    { 
     "id": "1", 
     "title": "The Shawshank Redemption", 
     "description": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", 
     "released": "2012-09-17 00:00:00" 
    }, 
    { 
     "id": "2", 
     "title": "The Godfather", 
     "description": "The aging <b>patriarch of an organized</b> crime dynasty transfers control of his clandestine empire to his reluctant son.", 
     "released": "2012-09-17 00:00:00" 
    } 
    ] 
} 

var $info = $('#info'); 
var source; 
//Grab contents of template 

function templateData(id){ 
    if(id == 'add1'){ 
     source = $("#infoTemp").html(); 
    } else { 
     source = $("#additionalInfoTemp").html(); 
    } 

    var template = Handlebars.compile(source); 
    $info.append(template(data)); 
} 

//Grab the container div and insert the templated data in 


$('button').on('click', function(e){ 
    var thisData = $(this).data('id'); 

    $info.html(''); 

    templateData(thisData); 

    e.preventDefault(); 
}); 

JS 바이올린 http://jsfiddle.net/2TpJh/2/

,536 JS

답변

0

당신은 각 변수의 존재를 확인하고 존재하는 경우에만 h1released을 렌더링 할 수 있습니다

<script type="text/x-handlebars" id="additionalInfoTemp"> 
    {{#each films}} 
    <li> 
     {{#id}}<h1>{{.}}</h1>{{/id}} 
     <h2>{{title}}</h2> 
     <p>{{{description}}}</p> 
     {{#released}}<small>{{.}}</small>{{/released}} 
    </li> 
    {{/each}} 
</script> 
+0

야, 문제는 데이터가 각 변수가 존재하는 것을 의미 두 차례에 걸쳐 동일 할 것입니다 ? – styler

+0

그런 다음 효과적으로 별도의 템플릿입니다. 템플리트를 다시 사용하려면 "id"또는 "released"를 제공하지 않는 다른 데이터보기를 작성할 수 있습니다. –

관련 문제