1

Is it possible to get the length of json object inside the handlebars template using the property .length .
{{json.length}}
If not is it possible to find the length based on the list of keys and then using the .length such as {{json.keys.length}}

Sample JSON structure

{1232134235423:[Name,Destination,Desc],  
 2134213214321:[Name],  
 2342354356634:[Name,Desc]
}

Edit 1:I know this can be achieved by using a custom helper but this length has to be used inside custom if helper. So something like array.length would be useful

vignesh
  • 37
  • 1
  • 8

3 Answers3

3

If I understand your edit right the problem is not to use another helper but to call it within another helper's call. Thus, you could use a second helper nested in your custom if-helper call:

{{#customIf (objectLength json)}}
    do some stuff...
{{/customIf}}

According to this answer "Getting JavaScript object key list" you can use Object.keys(json) to get all your object's keys.

The new helper objectLength could look like that:

Handlebars.registerHelper("len", function(json) {
    return Object.keys(json).length;
});
Community
  • 1
  • 1
TheAlxH
  • 71
  • 3
1

You can check length of object in handlebars template like this in your template. So HTML will render only when the object have one or more child element.

{
  people: [
    "abc",
    "Alan Johnson",
    "Charles Jolley",
  ],
}


{{#if people.length}}
  <p>{{ people}} </p>
  <ul class="people_list">
    {{#each people}}
      <li>{{this}}</li>
    {{/each}}
  </ul>
{{/if}}
Vijay Dhanvai
  • 1,054
  • 3
  • 13
  • 22
0

Yes it is possible. You first need to install handlebars helpers from npm (if not already) npm i handlebars-helpers then {{objectName.length}} will do the rest.