Reputation: 103
I am just starting out with handlebars so I apologise in advance if this is very simple or has already been answered (I cannot find anything searching).
I have a multi level json object that I want to display in my template. However I only want the top level elements displayed and not displaying if they have child properties.
Current Template:
<div id="example">
{{#each myObject}}
{{@key}}: {{this}}<br>
{{/each}}
</div>
Example Object:
{
a: value1,
b: value2,
c: value3,
d: { a: 1, b: 2, c: 3 },
e: value5
}
My desired (simplified) output is:
<div>
a: value1<br>
b: value2<br>
c: value3<br>
e: value5<br>
</div>
<div>
d<br>
a: 1<br>
b: 2<br>
c: 3<br>
</div>
What I am struggling with is how to add an if to my template in order to test if the property has a child object beneath it and not display it in the first section.
Then for each property that does have a child object, display it beneath (or elsewhere) and iterate through each of its child properties.
Any help would be much appreciated.
Upvotes: 0
Views: 441
Reputation: 161
You can achieve this by creating a helper function:
Handlebars.registerHelper('checkForJson', function (a) {
if(typeof a =='object')
{
return true;
}
return false;
});
And to use this in you html :
<div id="example">
{{#each .}}
{{#if (checkForJson this) }}
{{#each this}}
{{@key}}: {{this}}<br>
{{/each}}
{{else}}
{{@key}}: {{this}}<br>
{{/if}}
{{/each}}
</div>
Upvotes: 1