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

时间:2016-05-21 13:07:54

标签: javascript jquery json handlebars.js template-engine

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

这是我的模板(脚本):

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

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

1 个答案:

答案 0 :(得分:1)

这是因为你对每个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);

        }
    });
});