基于json键值的特定车把模板

时间:2014-11-27 10:36:19

标签: javascript jquery handlebars.js

我有一个配方API,它有不同类型的配方:Starter,Main,Dessert等。

我想做的是在一次调用中从API中获取所有数据,并让把手根据“类别”字段填充特定模板(这些模板相同但添加到不同的占位符)。但是,从下面的代码中,我将HTML注入到我的占位符div中但没有数据。奇怪的是,我也得到了4个模板数据实例。

这是我的代码:

对API的jQuery AJAX调用:

$( 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"}
]

我出错的任何想法?

1 个答案:

答案 0 :(得分:2)

首先,您需要将食谱分成不同的列表。

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