Luke Fox
Luke Fox

Reputation: 23

Handlebars displaying JSON data

I am trying to iterate over each item in a JSON array using handlebars. However I can't get any of the JSON data below to display. Here is my code:

HTML

{{#each entries}}
  <div class="entry">
    <h1>{{day}}</h1>
    <div class="body">
      {{content}}
    </div>
  </div>
{{/each}}

...

<script>

var entries = {

  entries: [
    {
      day: "Day 1",
      content: "THIS is TEST CONTENT"
    },
    {
      day: "Day 2",
      content: "THIS is TEST CONTENT2"
    }
  ]
};

</script>

I tried the same - http://tryhandlebarsjs.com/ and it worked perfectly, what seems to be the problem? Thanks.

Upvotes: 0

Views: 1643

Answers (1)

Shantanu Sharma
Shantanu Sharma

Reputation: 692

Try this Flow of this implementation :

HTML:

<h1>Handlebars JS Example</h1>
<script id="some-template" type="text/x-handlebars-template"> <table>
    <thead> 
        <th>Name</th> 
        <th>Job Title</th> 
        <th>Twitter</th> 
    </thead> 
    <tbody> 
        {{#users}} 
        <tr> 
            <td>{{person.firstName}}</td> 
            <td>{{jobTitle}}</td> 
            <td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td> 
        </tr> 
        {{/users}} 
    </tbody> 
</table> 
</script>

JAVASCRIPT CODE :

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

var data = { 
    users: [ { 
        person: {
            firstName: "Garry", 
            lastName: "Finch"
        },
        jobTitle: "Front End Technical Lead",
        twitter: "gazraa" 
    }, {
        person: {
            firstName: "Garry", 
            lastName: "Finch"
        }, 
        jobTitle: "Photographer",
        twitter: "photobasics"
    }, {
        person: {
            firstName: "Garry", 
            lastName: "Finch"
        }, 
        jobTitle: "LEGO Geek",
        twitter: "minifigures"
    } ]
}; 

$('body').append(template(data));

Upvotes: 1

Related Questions