Compile Handlebars templates and partials in Gulp

var gulp        = require('gulp'),
    uglify        = require('gulp-uglify'),
    rename        = require('gulp-rename'),
    concat        = require('gulp-concat'),
    handlebars    = require('gulp-handlebars'),
    wrap        = require('gulp-wrap'),
    path        = require('path'),
    htmlclean    = require('gulp-htmlclean'),
    merge        = require('merge-stream'),
    declare        = require('gulp-declare'),
    source        = require('vinyl-source-buffer'),

/**
 * Compile handlebars templates
 */
gulp.task('templates', function () {
    // Assume all partials start with an underscore
    // You could also put them in a folder such as source/templates/partials/*.hbs
    var partials = gulp.src( partials_source )
        .pipe( htmlclean() )
        .pipe( handlebars())
        .pipe( wrap('Handlebars.registerPartial(<%= processPartialName(file.relative) %>, Handlebars.template(<%= contents %>));', {}, {
            imports: {
                processPartialName: function(fileName) {
                    // Strip the extension and the underscore
                    // Escape the output with JSON.stringify
                    return JSON.stringify(path.basename(fileName, '.js').substr(1));
                }
            }
        }));
        
    var templates = gulp.src( templates_source )
        .pipe( htmlclean() )
        .pipe( handlebars() )
        .pipe( wrap('Handlebars.template(<%= contents %>)') )
        .pipe( declare({
            namespace : 'Publish.templates',
            noRedeclare : true
        }));

    return merge(partials, templates)
        .pipe( uglify() )
        .pipe( concat( 'publish.templates.js' ) )
        .pipe( rename( { suffix : '.min' } ) )
        .pipe( gulp.dest('./publish/assets/js') );
});

 

Leave a Reply