Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if value is an object in Handlebars?

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';
});
like image 881
dezman Avatar asked Dec 15 '22 04:12

dezman


1 Answers

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!

like image 135
megawac Avatar answered Dec 26 '22 22:12

megawac