Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile using Gulp handlebars partials to single HTML file

I would like to create a gulpfile to compile from partials into a single HTML file. This is my file structure:

| css/
| - main.css
| gulpfile.js
| less/
| - main.less
| index.html
| templates/
| - index.handlebars
| - partials /
| -- header.hbs
| -- footer.hbs

My gulpfile.js looks like this:

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var hbsAll = require('gulp-handlebars-all');
var handlebars = require('handlebars');
var gulpHandlebars = require('gulp-compile-handlebars')(handlebars); //default to require('handlebars') if not provided 
var rename = require('gulp-rename');
var less = require('gulp-less-sourcemap');
var autoprefixer = require('gulp-autoprefixer');
var watch = require('gulp-watch');


handlebars.registerPartial('header', '{{header}}'),
handlebars.registerPartial('footer', '{{footer}}')


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

    options = {
        partialsDirectory : ['./templates/partials']
    }

    return gulp.src('templates/index.handlebars')
        .pipe(gulpHandlebars( options))
        .pipe(rename('index.html'))
        .pipe(gulp.dest(''));
});

gulp.task('hbsToHTML', function() {
   gulp.src('templates/*.hbs')
  .pipe(hbsAll('html', {
    context: {foo: 'bar'},

    partials: ['templates/partials/*.hbs'],

  }))
  .pipe(gulp.dest('templates'));
});

gulp.task('less', function () {
  gulp.src('./less/*.less')
    .pipe(less({
        sourceMap: {
            sourceMapRootpath: '../less' // Optional absolute or relative path to your LESS files
        }
    }))
    .pipe(gulp.dest('./css'));
});

gulp.task('prefix', function () {
  return gulp.src('css/main.css')
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gulp.dest('./css'));
});

gulp.task('default', ['hbsToHTML', 'less', 'prefix']);

and my index.handlebars file looks like this:

{{> header}}
<p>Hello </p>
<p>there </p>
{{> footer}}

So, everthing else looks fine, but I can't get the hbsToHTML function to work. Any help is welcome! I know there could be more than a few bugs :(

like image 610
Nik Delig Avatar asked Oct 22 '25 14:10

Nik Delig


1 Answers

There's an excellent gulp plugin which does exactly this. You can find it on npm here: https://www.npmjs.com/package/gulp-compile-handlebars

Set the path to your partials using the batch option. Set the path to your templates using gulp.src and set the destination using gulp.dest

The example code on the npm page demonstrates this, though in your case you will not need the partials option and you may want to set the ignorePartials to false so that it picks up all the files you have in your partials directory

like image 167
rjbultitude Avatar answered Oct 25 '25 04:10

rjbultitude