javascript - Specific handlebars template based on json key value -
i have recipe api has different types of recipe: starter, main, dessert etc.
what i'd fetch of data api in 1 call , let handlebars populate particular template (these same added different placeholders) based on 'category' field. however, code below, html injected placeholder divs no data. strangely, 4 instances of template data well.
here's code:
jquery ajax call 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 , parmesan tartlets","category":"starter","imagepath":"/assets/recipes/asparagus_and_parmesan_tartlets.jpg"}, {"id":4,"title":"broad bean pate melba toasts","category":"main","imagepath":"/assets/recipes/broad_bean-pate.jpg"} ]
any ideas i'm going wrong?
first, need separate recipes 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 lists templates @ once.
$("#starters").html(templatestarter(starterlist)); $("#main").html(templatemain(mainlist));
here working jsfiddle.
Comments
Post a Comment