Skip to content

How to get same output as Handlebars CLI

Mario Basic edited this page Apr 26, 2014 · 3 revisions

Use this to get similar output like from handlebars CLI.

You can use the templates with Handlebars.templates.{{name}}(context, options) as specified in the handlebars documentation.

This task grabs all .hbs files, converts them to js functions using this plugin, concats them in one files and minifies that file.

You can run it as a watcher by running gulp from the command line or you can run it once with gulp handlebars.

var gulp = require('gulp');                     // main gulp thingy
var gutil = require('gulp-util');               // stops gulp from stopping on error
var concat = require('gulp-concat');            // merge js files together
var uglify = require('gulp-uglify');            // minify js file
var handlebars = require('gulp-handlebars');    // compile handlebar templates
var defineModule = require('gulp-define-module');
var declare = require('gulp-declare');

var handlebarsDir = "app/assets/templates";
var targetTemplateDir = "public/js";

gulp.task('handlebars', function(){
  gulp.src(handlebarsDir + '/**/*.hbs')
    .pipe(handlebars().on('error', gutil.log))
    .pipe(defineModule('plain'))
    .pipe(declare({
      namespace: 'Handlebars.templates'
    }))
    .pipe(concat('compiled.js'))
    .pipe(uglify().on('error',  gutil.log))
    .pipe(gulp.dest(targetTemplateDir));
});

gulp.task('watch', function() {
    gulp.watch(handlebarsDir + '/**/*.hbs', ['handlebars']);
})

gulp.task('default', ['handlebars', 'watch']);
Clone this wiki locally