簡體   English   中英

關於如何組合兩個都使用相同數據的把手模板的建議?

[英]advice about how I can combine 2 Handlebars templates that both use the same data?

我目前正在學習如何使用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/

您可以檢查每個變量的存在,使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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM