javascript - 基于json键值的特定 Handlebars 模板

标签 javascript jquery handlebars.js

我有一个食谱 API,其中包含不同类型的食谱:开胃菜、主菜、甜点等。

我想要做的是在一次调用中从 API 获取所有数据,并让 Handlebars 根据“类别”字段填充特定模板(这些模板相同,但添加到不同的占位符)。然而,从下面的代码中,我将 HTML 注入(inject)到占位符 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));
            } 
        });
    }
});
});

Handlebars 模板:

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

关于javascript - 基于json键值的特定 Handlebars 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27168503/

相关文章:

javascript - 如何使用两个按钮导航菜单?

javascript - 模型加载后 Ember.js 不重新渲染模板

javascript - Ember JS 和迭代而不影响结果计数

php - 来自所需 url 的嵌套 ID

Jquery Masonry 不适应不同的高度

javascript - sails.js 应用程序中的 Handlebars 布局和部分

javascript - 如何在 Javascript 中设置对象的动态属性?

javascript - 为什么我在 safari 和 chrome 中使用 JSON.stringify 来字符串化 json 会得到不同的结果?

Javascript 嵌套对象访问根级别

Javascript 验证 - 哪个最好(名称或 ID)