I\'m iterating over a list in Handlebars using the built-in each
helper.
Within the each block, I\'m referencing the current loop index
The handlebars-helpers library has a fairly thorough mathematics library in lib/math.js
, including a general purpose {{add a b}}
helper defined as follows:
/**
* Return the product of a plus b.
*
* @param {Number} a
* @param {Number} b
* @api public
*/
helpers.add = function(a, b) {
return a + b;
};
If you don't want to copy and paste this into your project and you have the possibility to use npm
, you can get this dependency as follows:
npm install handlebars-helpers --save
Then, you can register the math helpers as follows:
const handlebars = require('handlebars'),
handlebarsHelpers = require('handlebars-helpers');
handlebarsHelpers.math({
handlebars: handlebars
});
I believe you can use...
{{math @index "+" 1}}
Throwing my solution in here. CSS counters.
body {
counter-reset: section; /* Set a counter named 'section', and its initial value is 0. */
}
h3::before {
counter-increment: section; /* Increment the value of section counter by 1 */
content: counter(section); /* Display the value of section counter */
}
I was stuck on this and it was a nicer solution compared to adding a new helper.
there is an easy way to incitement with the {{@index}} value.
solution is to call the funtion and pass the @index value o it and than on JS, use helper to return @index + 1
here is go
{{incitement @index}}
and here is code for the js
Handlebars.registerHelper("incitement", function (inindex) {
return inindex + 1
});
I was using nodejs and express-handlebars as template engine and facing same problem. And this is how I managed to solve.
You can create a folder and a js file inside it where you can create your own custom helpers that takes index and returns incrementing it by 1.
module.exports = {
formatIndex: function(index) {
return index+1;
}
}
Remember to register helper in your application(in my case app.js). I have used express-handlebars so I have reistered helper in this way:
app.engine('handlebars', exphbs({defaultLayout: 'home', helpers: { formatIndex }}));
Note: You have to import formatIndex before registering.
Then you can use it in your view as:
{{#each assignments}}
<div>{{formatIndex @index }}</div>
{{/if}}
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}}