Handlebars does not have a lot of built-in support for logic. If your template requires some simple math, you are going to have to create one or more helpers.
In your case, you need to add 1
to your @index
and determine if this result is evenly divisible by your desired page size of 4
.
In the interest of having our helpers do one thing, I would recommend splitting this functionality into two helpers; I will call them sum
and isDivisor
.
sum
will take any number of Numbers as arguments and return the result of adding them all together:
Handlebars.registerHelper('sum', function () {
return Array.prototype.slice.call(arguments, 0, -1).reduce((acc, num) => acc += num);
});
isDivisor
will take two Numbers as arguments and will return true
if the first Number is a divisor of the second; otherwise false
:
Handlebars.registerHelper('isDivisor', function (num1, num2) {
return num1 !== 0 && num2 % num1 === 0;
});
Handlebars' subexpressions are delimited by parentheses, so what should go in your IF is the following:
{{#if (isDivisor 4 (sum @index 1))}}
For reference, I have created a fiddle.
However, although the above answers your question, I believe there is a better way to solve your problem.
I think the better solution would be to create a block helper that will slice your Array into chunks of your desired page size and then apply a template to each chunk, before concatenating and rendering the result. Such an implementation would look like the following:
Handlebars.registerHelper('page', function (arr, pageSize, options) {
var result = [];
for (var i = 0; i < arr.length; i += pageSize) {
result.push(options.fn({ items: arr.slice(i, i + pageSize) }));
}
return result.join('');
});
The options.fn
bit is the interesting part. It is applying our template block to a data object with a single property, items
, which is a paged slice of our original array. The way we would use this helper in our template is as follows:
{{#page Badges 4}}
<div class="container">
{{#each items}}
<div class="cardContainer">
{{! TODO: Copy inner template and paste here. }}
</div>
{{/each}}
</div>
{{/page}}
For reference, I have created another fiddle.