[英]Specific handlebars template based on json key value
I have a recipe API that has different types of recipe: Starter, Main, Dessert etc. 我有一个配方API,其中包含不同类型的配方:入门,主,甜点等。
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. 我想做的是一次调用即可从API中获取所有数据,然后让车把基于“类别”字段填充特定模板(这些模板相同,但添加到不同的占位符)。 However, from my code below, I get HTML injected into my placeholder divs but with no data.
但是,从下面的代码中,我将HTML注入到占位符div中,但是没有数据。 Strangely, I get 4 instances of the template data as well.
奇怪的是,我也得到了4个模板数据实例。
Here's my code: 这是我的代码:
jQuery AJAX call to API: jQuery AJAX对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: 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? 有什么想法我要去哪里吗?
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.