Question

I am having a handlebar template which takes a JSON object.

Handle Bar Code -

<script id="list" type="x-handlebars-template">
{{#each items}} {{! Each item is an "li" }}
<li>
    {{label}} :
    {{value}}
    {{#if items}}
    <ul>
    {{> list}} {{! Recursively render the partial }}
    </ul>
    {{/if}}
</li>
{{/each}}

<script id="main" type="x-handlebars-template">
    <ul>
        {{> list}}
    </ul>
</script>

The JSON object as -

var items =[
  { "label": "TotalRented", "value": "5" },
  { "label": "AncilleryItems", "items": [
    { "label": "Item", "value": "CarSeat" },
    { "label": "Qty", "value": "2" },
    { "label": "Cost","items": [
          { "label": "VAT", "value": "$20" },
          { "label": "Total", "value": "$100" }
      ]
    },
    { "label": "Item", "value": "GPS" },
    { "label": "Qty", "value": "1" },
    { "label": "Cost", "items": [
          { "label": "VAT", "value": "$10" },
          { "label": "Total", "value": "$50" }
      ]
    }
  ]
  },
  { "label": "Colour", "value": "red" }
 ];

// The main template.
var main = Handlebars.compile( $( "#main" ).html() );

// Register the list partial that "main" uses.
Handlebars.registerPartial( "list", $( "#list" ).html() );

// Render the list.
$( "body" ).html( main( { items: items } ) );

This code would render the tree structure data properly for me as in the fiddle - http://jsfiddle.net/achyut/V6HNd/1/

Now my JSON object has been changed and it now has extra square brackets, for logical seperation. I am not able to render the tree structure with extra brackets now. Can anyone tell what code needs to be changed in the handlebar template.

The new JSON object is

var items = [
  { "label": "TotalRented", "value": "5" },
  { "label": "AncilleryItems", "items": [
  [
    { "label": "Item", "value": "CarSeat" },
    { "label": "Qty", "value": "2" },
    { "label": "Cost","items": [
        [
          { "label": "VAT", "value": "$20" },
          { "label": "Total", "value": "$100" }
        ]
      ]
    }
  ],
  [
    { "label": "Item", "value": "GPS" },
    { "label": "Qty", "value": "1" },
    { "label": "Cost", "items": [
        [
          { "label": "VAT", "value": "$10" },
          { "label": "Total", "value": "$50" }
        ]
      ]
    }
  ]
 ]
},
{ "label": "Colour", "value": "red" }
]
Was it helpful?

Solution

Since you have array of items, you have to loop it again and to access the object you can use this

{{#each items}} 
   {{#each this}} {{! Each item is an "li" }}

     {{! Code here }}

   {{/each}}
{{/each}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top