Mick
Mick

Reputation: 2898

iterate through Child elements in Handlebars

As an example I have the following dataset

  dataset = {header: ' header' } 

  dateline = { content: 'list of dates' } 

  monday = [
        { food:'teacake' , drink:'orange' } 
        ]

  tuesday = [
        { food:'eggs' , drink:'beer' } 
        ]    

  dateline.monday = monday
  dateline.tuesday = tuesday
  dataset.dateline = dateline 

What I want to do is use handle bars to run though the days , I thought this could be done using child.

  <script id="mwl707" type="text/x-handlebars-template">        
  {{#each dateline.children }}
    <span>{{food}} : {{drink}}</span>
  {{/each}}
  </script>

but I cant get it to work , any help please ? JSfiddle

Upvotes: 0

Views: 1846

Answers (2)

tmaximini
tmaximini

Reputation: 8503

I updated your fiddle so it works: http://jsfiddle.net/AgCBb/1/

You should not wrap your objects monday and tuesday again in [] parenthesis, it is an unnecessary extra level to parse. Just make an days Array in your parent object, as arrays are much easier to parse in Handlebars.

dataset = {header: ' header' } //
dateline = { content: 'list of dates' } 
monday  =  { "food":"teacake" , "drink":"orange" }
tuesday = { "food":"eggs" , "drink":"beer" }

dateline.days = []
dateline.days.push(monday)
dateline.days.push(tuesday)

Then you can parse it like this:

{{#dateline.days }}
  <span>{{food}} : {{drink}}</span>
{{/dateline.days}}

Also make sure you pass valid JSON to your templates. If unsure you might check your JSON with http://jsonlint.com/

Upvotes: 1

ryan
ryan

Reputation: 6655

Handlebars does not provide a built-in way to iterate properties of an object. See Handlebars/Mustache - Is there a built in way to loop through the properties of an object?. You can instead format your data in such a way that Handlebars supports such as a plain array. I won't duplicate the code here, it is in the linked post.

Also, you shouldn't be placing <script> tags inside a fiddle's javascript plain. Use the External Resources section instead.

Upvotes: 0

Related Questions