Handlebars separate list into multiple templates

by Csaba Hellinger

HTML

<script src="http://www.fsfoo.com/js/vendor/handlebars-1.0.rc.2.js"></script>
<script id="startertemplate" type="text/x-handlebars-template">
    {{#each this}}
    <div class="col-sm-6">
        <h3>{{Title}}</h3>
        <img src="{{ImagePath}}" alt="{{Title}}" height="200" width="300" /><br />
        <a href="recipe.html?id={{ID}}">See more</a>
    </div>
    {{/each}}
</script>

<script id="maintemplate" type="text/x-handlebars-template">
    {{#each this}}
    <div class="col-sm-6">
        <h3>{{Title}}</h3>
        <img src="{{ImagePath}}" alt="{{Title}}" height="200" width="300" /><br />
        <a href="recipe.html?id={{ID}}">See more</a>
    </div>
    {{/each}}
</script>

<div id="starters"></div>
<div id="main"></div>

CSS

#starters {
    background-color: skyblue;
}

#main {
    background-color: pink;
}

JavaScript

var msg = [
        {"ID":1,"Title":"Aioli","Category":"Starter","ImagePath":"http://images.media-allrecipes.com/userphotos/250x250/00/39/71/397173.jpg"},
        {"ID":3,"Title":"Asparagus and Parmesan Tartlets","Category":"Starter","ImagePath":"http://www.kraftrecipes.com/assets/recipe_images/Asparagus-Parmesan-Tart-57918.jpg"}, 
        {"ID":4,"Title":"Broad Bean Pate with Melba Toasts","Category":"Main","ImagePath":"http://www.farnhamfood.com/wp-content/uploads/2011/07/broad-bean-pate.jpg"}
    ],

    sourceStarter = $("#startertemplate").html(),
    templateStarter = Handlebars.compile(sourceStarter),
    starterList = [],
    
    sourceMain = $("#startertemplate").html(),
    templateMain = Handlebars.compile(sourceMain),
    mainList = [];

// first, separate records into lists, based on category
$.each(msg, function (i, o) {
    if (o['Category'] === "Starter") {
        starterList.push(o);
    } if (o['Category'] === "Main") {
        mainList.push(o);
    }
});

// then give the whole list to the template at once
$("#starters").html(templateStarter(starterList));
$("#main").html(templateMain(mainList));