基于 json 密钥值的特定车把模板

Specific handlebars template based on json key value

本文关键字:json 密钥 基于      更新时间:2023-09-26

我有一个食谱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。