0

我目前正在学习如何使用 Handlebars 进行模板化,并且想要一些关于如何将以下 2 个模板组合为 1 个并更新我的脚本以使每个按钮仍显示正确的值集的建议?

模板

<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>

JS

// 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/

​</p>

4

1 回答 1

0

您可以检查每个变量是否存在,并仅在它们存在时才呈现h1和:released

<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>
于 2012-10-10T19:07:06.057 回答