3

I have just recently moved from grunt to gulp and I am wanting to pre-compile my handlebars templates (with .handlebars extension) into separate .js files.

from:

  • www/templates/login.handlebars
  • www/templates/home.handlebars

to:

  • www/templates/login.js
  • www/templates/home.js

I am trying to use gulp but to no avail. A lot of the npm packages ask you to pass data to the compiler, but the data in my web app is collected mainly from ajax requests and then passed to the handlebars template.

My gulpfile.js:

// cache vars
var gulp = require('gulp'),
    rename = require('gulp-rename'),
    handlebars = require('gulp-compile-handlebars');

// start task
gulp.task('default', function(){

    return gulp.src( 'www/templates/*.handlebars' )
        .pipe( handlebars() )
        .pipe( rename('*.js') )
        .pipe( gulp.dest( 'www/templates' ) );
    });

});

The main reason i moved from Grunt to Gulp was because grunt doesnt seem to support the newer handlebars version (link here).

There are lots of examples how to compile handlebars templates but not in the way I want too (Is my way possible?)

Also i don't want to wrap my handlebar js files into a namespace if possible.

When i run my gulp task none of the .js files are generated any ideas?

pleshy
  • 1,468
  • 2
  • 16
  • 22

1 Answers1

1

I have a not so clean solution that works for me. I'm using pump + gulp as it's a good idea to clean the source if something goes wrong while processing the pipe.

in the gulpfile.js:

const pump = require( 'pump' )
const handlebars = require( 'gulp-handlebars' )

gulp.task( 'default', ( done ) => {

    const templates = [
        'login',
        'home'
    ] // <-- You may want to get the list of files programmatically ;)

    let pipe = []

    templates.forEach( ( template ) => {
        pipe.push( gulp.src( 'www/templates/' + template + '.handlebars' ) )
        pipe.push( handlebars() )
        pipe.push( gulp.dest( 'www/templates/' ) )
    } )

    pump( pipe, done )

} )
tiomno
  • 2,178
  • 26
  • 31
  • do we have some similar plugin for Gradle too , for same functionality? – KCS Jun 28 '18 at 06:52
  • @Chandra I know nothing about Gradle, but this project might be of help. Check it out https://github.com/djoly/ant-handlebars/blob/master/samples/gradle/build.gradle of https://github.com/djoly/ant-handlebars – tiomno Jun 28 '18 at 07:15