0

I'm trying to use handlebars in my project, but am running into trouble getting it to output each object's attributes.

Data

people: [{"name":"Moe"}, {"name":"Larry"}, {"name":"Curly"}]

Template

{{#people}} Name: {{name}} <br/>{{/people}}

Output

Name: 
Name: 
Name: 

It obviously reads the list of people, because it outputs three times. but I don't know why it's not able to see the simple path to name.

  • If I put {{this.name}}, it also renders a blank.
  • If I put {{this}}, I see [object Object].

How do I log or investigate this object so I know why the name attribute isn't being rendered?

Matt Norris
  • 8,596
  • 14
  • 59
  • 90

2 Answers2

0

try {{#each people}} Name: {{name}} <br/>{{/each}}

Gwyn Howell
  • 5,365
  • 2
  • 31
  • 48
  • Unfortunately, I did try that with the same result. Thank you, though. – Matt Norris Apr 13 '12 at 11:22
  • How are you passing the data into the template? For example `template(people)` won't work, but `template({people:people})` probably will – Gwyn Howell Apr 13 '12 at 13:05
  • Having now looked closer at your dataset, you have a hash with 3 identical keynames, so they're just overwriting each other. I assume what you mean to do it do have a list, which would be like this: people: [{"name":"Moe"}, {"name":"Larry"}, {"name":"Curly"}] or, maybe ever simpler would be: people: ["Moe","Larry","Curly"] – Gwyn Howell Apr 14 '12 at 16:14
  • Thanks for catching my typo. It actually is the first example you listed. I've updated my question accordingly. – Matt Norris Apr 15 '12 at 02:20
0

Something must be wrong with the rest of your code, in this fiddle it works:

http://jsfiddle.net/hDE3P/

var context = {
   people : [{"name":"Moe"}, {"name":"Larry"}, {"name":"Curly"}] 
} 
var source   = $("#entry").text();
var template = Handlebars.compile(source);
$("#out").html( template(context) );

with this html

<script id="entry" type="text/x-handlebars-template">
    {{#people}} Name: {{name}} <br/>{{/people}}
</script>

output:  
<div id="out"></div>

Try these things:

  • Check your datamodel in the debugger (Firebug or sth.)
  • Check your template is correct (sometimes browsers destroy it if not in script tags)
  • Debug into Handlebars "each" handler to see what the context looks like

Hope this helps.

da maddin
  • 149
  • 1
  • 3