Reputation: 195
I'm running some Gulp tasks and using handlebars.js for html templating, but I'm struggling to get helper functions to work from an external js file... The documentation here doesn't really explain how the external file should look, so I'm hoping someone can help me out.
Here's what I have
/**** gulpfile.js ****/
var gulp = require('gulp');
var hb = require('gulp-hb');
gulp.task('default', function () {
return gulp
.src('./src/{,posts/}*.html')
.pipe(hb({
partials: './src/assets/partials/**/*.hbs',
helpers: './src/assets/helpers/*.js',
data: {
people: [
{firstName: "Yehuda", lastName: "Katz"},
{firstName: "Carl", lastName: "Lerche"},
{firstName: "Alan", lastName: "Johnson"}
]
}
}))
.pipe(gulp.dest('./web'));
});
/**** External js file .../helpers/helpers.js ****/
Handlebars.registerHelper('list', function(items, options) {
var out = "<ul>";
for(var i=0, l=items.length; i<l; i++) {
out = out + "<li>" + options.fn(items[i]) + "</li>";
}
return out + "</ul>";
});
<!-- Handlebars html template -->
{{#list people}}{{firstName}} {{lastName}}{{/list}}
Shoots out an error message:
[14:10:13] ReferenceError: Handlebars is not defined
at Object.<anonymous> (/Applications/MAMP/htdocs/helpers/src/assets/helpers/helpers.js:1:63)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at mapper (/Applications/MAMP/htdocs/helpers/node_modules/gulp-hb/node_modules/handlebars-wax/node_modules/require-glob/src/require-glob.js:51:12)
at Array.map (native)
at mapReduce (/Applications/MAMP/htdocs/helpers/node_modules/gulp-hb/node_modules/handlebars-wax/node_modules/require-glob/src/require-glob.js:87:4)
Upvotes: 0
Views: 2096
Reputation: 5704
Update Sorry, I should have looked at the docs more carefully.
You should add functions to helpers property in object you pass to
hb({
helpers:{
list: function (){}
}
})
Or if you pass a path to helpers file, you just export object with functions, so you don't need access to HandleBars at all.
//helpers.js
module.exports = {
list: function (){}
};
Incorrect You need to require the gulp-hb module and use its property handlebars.
var HandleBars = require('gulp-hb').handlebars;
HandleBars.registerHelper(...);
Upvotes: 2