基于 json 密钥值的特定车把模板
Specific handlebars template based on json key value
我有一个食谱API,其中包含不同类型的食谱:开胃菜,主菜,甜点等。
我想做的是在一次调用中从 API 获取所有数据,并让车把根据"类别"字段填充特定模板(这些模板相同但添加到不同的占位符)。但是,从下面的代码中,我将 HTML 注入到我的占位符div 中,但没有数据。奇怪的是,我也得到了 4 个模板数据的实例。
这是我的代码:
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));
}
});
}
});
});
车把模板:
<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>
示例 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"}
]
有什么想法我哪里出错了吗?
首先,您需要将配方分成不同的列表。
var starterList = [],
mainList = [];
$.each(msg, function (i, o) {
if (o['Category'] === "Starter") {
starterList.push(o);
} if (o['Category'] === "Main") {
mainList.push(o);
}
});
然后立即将列表提供给模板。
$("#starters").html(templateStarter(starterList));
$("#main").html(templateMain(mainList));
这是一个工作 jsfiddle。
相关文章:
- 加载两个具有相同父密钥名称的json文件
- D3动态json密钥名称
- 根据用户选择获取 JSON 密钥
- 从包含密钥路径的字符串中获取json值
- 如何在javascript中获取数组密钥对的json子值
- node.js JSON.parse reviver没有't报告重复的密钥
- 仅使用该值检索 JSON 密钥
- 当我不知道密钥的名称时,如何读取 JSON 对象
- 动态创建 json 密钥
- 循环访问没有数组的 JSON 密钥对象
- 如何在 json 密钥中访问 Json 密钥
- 基于 json 密钥值的特定车把模板
- 使用正则表达式转换 JSON 密钥值
- 如何将 JSON 密钥转换为值
- 带有美元符号的JSON密钥
- 找不到JSON密钥
- 只加密json密钥值,并获得整个json对象的响应与密钥值加密
- TypeScript:使用函数参数作为JSON密钥名称
- 获取 JSON 密钥名称
- JSON 密钥存在,但返回 false