Farid Rn
Farid Rn

Reputation: 3207

Implementing loop of handlebars.js on nameless object or array

All of Handlebars examples are implementing loops with array or object names, but my json array doesn't have any names.

My data is something like:

[
    {"$id":"1","SiteItemID":1,"Title":"Title 1","CreateDate":"2014-06-19T14:12:22.157"},
    {"$id":"2","SiteItemID":2,"Title":"Title 2","CreateDate":"2014-06-19T14:12:22.157"},
    {"$id":"2","SiteItemID":3,"Title":"Title 3","CreateDate":"2014-06-19T14:12:22.157"},
]

I want to use them in table rows and my html is something like:

{{#each object}}
<tr data-id="{{this.SiteItemID}}">
    <td class="title col-xs-8">
        {{this.Title}}
    </td>
    <td class="date text-right col-xs-2">
        {{this.CreateDate}}
    </td>
</tr>
{{else}}
No Content
{{/each}}

And I'm putting them together with following JS code:

function getData() {
    $.ajax({
        url: 'http://192.168.101.223:81/api/siteitem'
        , success: function(data) {
            return data;
        }
    });
}
function showData() {
    var data = getData();
    var template = $("#itemlist-table").html();
    var handlebarsTemplate = Handlebars.compile(template);
    var output = handlebarsTemplate(data);
    $("#mainbody").html(output);
}
showData();

And I have tried {{#each object}} and {{#each array}}, but both of them result in 'No Content'.

Am I doing something wrong?

Upvotes: 0

Views: 222

Answers (1)

ckross01
ckross01

Reputation: 1671

you need to use {{#each []}}

{{#each []}}
<tr data-id="{{this.SiteItemID}}">
    <td class="title col-xs-8">
        {{this.Title}}
    </td>
    <td class="date text-right col-xs-2">
        {{this.CreateDate}}
    </td>
</tr>
{{else}}
No Content
{{/each}}

here is my fiddle

http://jsfiddle.net/ckross01/K49xy/

Upvotes: 2

Related Questions