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

各変数の存在を確認し、それらが存在する場合にのみh1andをレンダリングできます。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 に答える