Brett
Brett

Reputation: 1973

Specific handlebars template based on json key value

I have a recipe API that has different types of recipe: Starter, Main, Dessert etc.

What I'd like to do is to fetch all of the data from the API in one call and let handlebars populate a particular template (these are the same but added to different placeholders) based on the 'Category' field. However, from my code below, I get HTML injected into my placeholder divs but with no data. Strangely, I get 4 instances of the template data as well.

Here's my code:

jQuery AJAX call to API:

$( document ).ready(function() {
 $.ajax({
     type: "GET",
     url: "http://example.org/api/recipes",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (msg) {           

        var source;
        var template;

        $.each(msg, function (i, o) {
            if (o['Category'] === "Starter") {
                source = $("#startertemplate").html();
                template = Handlebars.compile(source);
                $("#starters").html(template(o));
            } else if (o['Category'] === "Main") {
                source = $("#maintemplate").html();
                template = Handlebars.compile(source);
                $("#main").html(template(o));
            } 
        });
    }
});
});

Handlebars template:

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

Example JSON:

[
    {"ID":1,"Title":"Aioli","Category":"Starter","ImagePath":"/assets/recipes/Aioli.jpg"},
    {"ID":3,"Title":"Asparagus and Parmesan Tartlets","Category":"Starter","ImagePath":"/assets/recipes/Asparagus_and_Parmesan_Tartlets.jpg"}, 
    {"ID":4,"Title":"Broad Bean Pate with Melba Toasts","Category":"Main","ImagePath":"/assets/recipes/Broad_bean-pate.jpg"}
]

Any ideas where I'm going wrong?

Upvotes: 0

Views: 603

Answers (1)

zord
zord

Reputation: 4783

First, you need to separate the recipes into different lists.

var starterList = [],
    mainList = [];
$.each(msg, function (i, o) {
    if (o['Category'] === "Starter") {
        starterList.push(o);
    } if (o['Category'] === "Main") {
        mainList.push(o);
    }
});

Then give the lists to the templates at once.

$("#starters").html(templateStarter(starterList));
$("#main").html(templateMain(mainList));

Here is a working jsfiddle.

Upvotes: 2

Related Questions