jsBin Example
Here is my little model:
var stuff = [{
there: 'blah',
that: {
one: 'bbb',
two: 'ccc'
}
}];
First, for the following template, I don't understand why the first {{@key}}
doesn't output anything and the second one does.
{{#each this}}
{{@key}}
{{#each that}}
{{@key}}
{{/each}}
{{/each}}
And more importantly I am trying to use this next template and a helper to check if a value is an object or a string and either iterate over it and print the keys, or just print out the key.
{{#each this}}
{{#if isObj this}}
{{#each that}}
{{@key}}
{{/each}}
{{else}}
{{@key}}
{{/if}}
{{/each}}
Helper:
Handlebars.registerHelper('isObj', function(thing) {
return $.type(thing) === 'object';
});
The first one I can answer, you should use {{@index}}
instead of {{@key}}
because your iterating an array. I'm looking into the second one.
A:
{{#each this}}
key: {{@index}}
{{#each that}}
key1: {{@key}}
{{/each}}
{{/each}}
For part b it seems you're going to have to register a new helper function as if cant take the return from another funciton. You're block helper will be something like (pretty much stole this from here):
Handlebars.registerHelper('ifObject', function(item, options) {
if(typeof item === "object") {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Now change your template to something like:
{{#each this}}
{{#ifObject this}}
{{#each that}}
{{@key}}
{{/each}}
{{else}}
{{@key}}
{{/ifObject}}
{{/each}}
This was working on tryhandlebars.com and updated your jsbin, hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With