How to get array length and check an array is empty in HandlebarJS
- Admin
- Mar 10, 2024
- Javascript-examples
In this short tutorial, Learned about how to find the array length in handlebar template javascript with examples.
You can do it in two ways
- Use the javascript array length function
{{each}}
helper classes are used to iterate iterable object types. It provides variables such as the@length
attribute to return the length of an array.@length
works inside the{{each}}
section, However, does not work outside the section.- Custom helper function to get array size elements.
Array length in handlebar javascript
The length
variable inside each section, returns several elements in an array.
{{array.length}}
let’s declare json object
{
numbers: ["one", "two", "three"];
}
Inside the JSON object, numbers is an array, containing the sequence of strings
In html template, use {{numbers.length}}
to check length of an array
Total records - {{numbers.length}}
Output rendered is
Total records - 3
Use each @length variable
#each
section is used to iterate an array of elements. You can use the @length
variable to get the array size
{{#each array}}
<span>{{this}} {{@length}} </span>
{{/each}}
It prints the size for each element, not recommended to use for this, you can use another variable such as @index
, @first
, or @last
.
Helper functions to check the length of an array
Let’s declare a customer helper class and register seen below.
Handlebars.registerHelper("arraySize", function (data) {
return data.length;
});
In the template access the helper class using double brace syntax
{{arraySize numbers}} // returns 3
How to check array or list is empty in the handlebar
Sometimes, we want to check array length is zero or the array size is empty.
We have to use handlebar if condition
array.length will not work without if the block in the handlebars.
Instead, you can use an array to check array is empty or not
<div>
{{#if numbers }}
<p>Number array length is {{numbers.length}}</p>
{{else }} Array is empty {{/if}}
</div>
We can also write a custom helper to check if the array length is empty or greater than 3
<div>
{{#isArrayEmpty numbers 0}} array length is empty {{else }}
<p>Number array length is {{numbers.length}}</p>
{{/isArrayEmpty }}
</div>
We have to register a custom helper
Handlebars.registerHelper("isArrayEmpty", function (a, b, options) {
"use strict";
if (a.length === b) {
return options.fn(this);
}
return options.inverse(this);
});
Conclusion
You have learned how to check array length and check array, or object, or list is empty.