Question

I am having a hard time understanding how to deal with a top level array of dictionaries using handlebars.js with jQuery

My data object does not consist of a dictionary with a named array object (which is what most of the examples online deal with). My data object looks like this:

[
  {
    "Type": "TopLevel",
    "Identifier": "123456789IL",
    "FullName": "Smith, John H.",
    "CurrentLocation": "In Building"
  },
  {
    "Type": "TopLevel",
    "Identifier": "123456789OL",
    "FullName": "Doe, Jane M.",
    "CurrentLocation": "Parking Lot"
  }
]

Here is a jsfiddle of a working (using the named array object (which I don't have) and a non-working jsfiddle with my actual data object (doesn't work).

http://jsfiddle.net/eljaywilson/ZhF5h/ - works, but not how my data object looks

http://jsfiddle.net/eljaywilson/ZhF5h/1/ - no worky

Was it helpful?

Solution

You have an error in your template - you will have to change [/users] to {{/.}} like this:

    <tbody> 
        {{#.}}
        <tr> 
            <td>{{Type}}</td> 
            <td>{{FullName}}</td> 
            <td>{{CurrentLocation}}</td> 
            <td>{{Identifier}}</td> 
        </tr> 
        {{/.}}
    </tbody> 

OTHER TIPS

This should solve your problem:

var source = $("#some-template").html(); 
var template = Handlebars.compile(source); 

var data =  [
  {
    "Type": "TopLevel",
    "Identifier": "123456789IL",
    "FullName": "Smith, John H.",
    "CurrentLocation": "In Building"
  },
  {
    "Type": "TopLevel",
    "Identifier": "123456789OL",
    "FullName": "Doe, Jane M.",
    "CurrentLocation": "Parking Lot"
  }
]
; 

Handlebars.registerHelper('fullName', function(person) {
  return person.firstName + " " + person.lastName;
});

$('#myDiv').append(template({ users: data }));

Explanation:

data is an array and you just wrap it before passing to a template.

Fixed jsfiddle is here: http://jsfiddle.net/akhikhl/bTzf3/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top