使用 Handlebars 模板引擎传递 JSON 数组

Pass through JSON array using Handlebars template engine

这是我的 JSON,我想知道如何使用 handlebars 模板引擎将我的信息显示到页面中:

这是我的模板(脚本):

<script id="template-app" type="text/x-handlebars-template">
    {{#each data}}
        Email: {{email}} <br/>
        First Name: {{first_name}} <br/>
        Last Name: {{last_name}} <br/>
    {{/each}}
</script>

然后我发送一个 ajax 请求以获得以下 JSON:

$(function(){
    var theTemplateScript= $("#template-app").html();
    var theTemplate= Handlebars.compile(theTemplateScript);

    $.ajax({
        url: 'http://localhost/cb/MOCK_DATA.json',
        type: 'GET',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            var theCompiledHTML= theTemplate(data);
            $(document.body).append(theCompiledHTML);

        }
    });
});

这是上面Ajax请求得到的JSON:

[{"first_name":"Betty","last_name":"Sims","email":"bsims0@studiopress.com"},
{"first_name":"Roger","last_name":"Mendoza","email":"rmendoza1@google.pl"},
{"first_name":"Albert","last_name":"West","email":"awest2@cornell.edu"},
{"first_name":"Bobby","last_name":"Lane","email":"blane3@ameblo.jp"},
{"first_name":"Julie","last_name":"Wheeler","email":"jwheeler4@google.ru"}]

它不起作用,我相信它来自我编写的模板!

这是因为你说的是​​对每个 data,遍历数组。但是,您将一个普通的旧数组传递给 Handlebar 模板。它需要一个具有 属性 data 和数组值的对象。因此,您可以将 Handlebars 模板更改为:-

<script id="template-app" type="text/x-handlebars-template">
    {{#each this}}
        Email: {{email}} <br/>
        First Name: {{first_name}} <br/>
        Last Name: {{last_name}} <br/>
    {{/each}}
</script>

--

或者 ,您可以调整 JSON 数据以使用现有的 Handlebars 模板,如下所示:-

var json = {
    data: [{
        "first_name": "Betty",
        "last_name": "Sims",
        "email": "bsims0@studiopress.com"
    }, {
        "first_name": "Roger",
        "last_name": "Mendoza",
        "email": "rmendoza1@google.pl"
    }, {
        "first_name": "Albert",
        "last_name": "West",
        "email": "awest2@cornell.edu"
    }, {
        "first_name": "Bobby",
        "last_name": "Lane",
        "email": "blane3@ameblo.jp"
    }, {
        "first_name": "Julie",
        "last_name": "Wheeler",
        "email": "jwheeler4@google.ru"
    }]
};

对于您的 JavaScript 代码,您只需稍作更改即可获得上述 JSON:

$(function(){
    var theTemplateScript= $("#template-app").html();
    var theTemplate= Handlebars.compile(theTemplateScript);
    $.ajax({
        url: 'http://localhost/cb/MOCK_DATA.json',
        type: 'GET',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            var json_handlbars={
                data:result
            };
            var theCompiledHTML= theTemplate(json_handlbars);
            alert(theCompiledHTML);
            $(document.body).append(theCompiledHTML);

        }
    });
});