Search code examples
javascriptgulphandlebars.jsprecompile

How to precompile gulp-handlebars helpers?


I am precompiling my templates into JS using gulp-handlebars but I am having trouble getting custom handlebars helpers to also precompile. Does anyone know if there is any support/way to precompile custom helper methods?


Solution

  • I noticed that gulp-handlebars can use a specific handlebars library, essentially overriding its default. So, by just creating my own module and registering some helpers, and feeding that into the handlebars call, things are working locally.

    // helpers.js
    var handlebars  = require('handlebars');
    
    handlebars.registerHelper('upper', function(str){
       return str.toUpperCase();
    });
    
    module.exports = handlebars;
    

    And then in the gulpfile (something like this):

    var handlebars = require('./src/js/helpers.js');
    
    gulp.task('handlebars', function(){
      gulp.src('src/html/*.html')
          .pipe(gulp_handlebars({handlebars: handlebars})) // override library here
    });