Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  11] [ 5]  / answers: 1 / hits: 39984  / 9 Years ago, sat, october 10, 2015, 12:00:00

I am using handlebars.js templates with node and express. I am making a numbered list using the {{@index}} template tag, however since index starts at 0 and I want to start from one, it seems I need to use a custom helper. I've seen plenty of posts regarding this and I've found the following code:



Handlebars.registerHelper(inc, function(value, options)
{
return parseInt(value) + 1;
});

{{#each score}}
<li class=list-group-item>
<div id=place> {{inc @index}} &nbsp </div>
<div class=wordOrName>{{ player_name }}</div>
<div class=number>{{ score }}</div></li>
{{/each}}


What I cannot seem to find is where the helper register function is supposed to go. I've tried putting it inside in the template itself and in various other places but I still keep getting



Error: Missing helper: inc
at model.<anonymous>


Ideally I'd like to have the helper in a separate file helpers.js but I don't have the slightest idea of how to get handlebars to recognize it.



EDIT:



Handlebars is included in the project with the following code inside the node file index.js:



// view engine
app.set('views', __dirname + '/views/');
app.set('view engine', 'handlebars');
app.engine('handlebars', engines.handlebars);


It appears impossible to include the helper function within the template itself.


More From » node.js

 Answers
235

I figured it out...The helpers indeed need to be registered in the node app file like so:



// view engine
app.set('views', __dirname + '/views/');
app.set('view engine', 'handlebars');
var hbs = require('handlebars');
hbs.registerHelper(inc, function(value, options)
{
return parseInt(value) + 1;
});
app.engine('handlebars', engines.handlebars);


I wish this info was more easily accessible, but there it is.


[#64778] Wednesday, October 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;