Adding offset to {{@index}} when looping through items in Handlebars
Actual answer: https://stackoverflow.com/a/46317662/1549191
Register a math handlebar and perform all mathematical operations.
app.engine('handlebars', exphbs({
helpers:{
// Function to do basic mathematical operation in handlebar
math: function(lvalue, operator, rvalue) {lvalue = parseFloat(lvalue);
rvalue = parseFloat(rvalue);
return {
"+": lvalue + rvalue,
"-": lvalue - rvalue,
"*": lvalue * rvalue,
"/": lvalue / rvalue,
"%": lvalue % rvalue
}[operator];
}
}}));
app.set('view engine', 'handlebars');
Then you can directly perform operation in your view.
{{#each myArray}}
<span>{{math @index "+" 1}}</span>
{{/each}}
Handlebars gives you the possibility to write a custom helper that handles this situation, e.g. a helper function that lets you perform calculations on expressions like addition and subtraction etc.
Below function registers a new helper, which simply increments a value by 1:
var Handlebars = require('handlebars');
Handlebars.registerHelper("inc", function(value, options)
{
return parseInt(value) + 1;
});
You can then use it within the handlebar expression using the inc
keyword, like:
{{inc @index}}
I believe you can use...
{{math @index "+" 1}}