Skip to content

Instantly share code, notes, and snippets.

@jbenner-radham
Created September 8, 2014 04:02
Show Gist options
  • Save jbenner-radham/2a8721b1bf357b91fc66 to your computer and use it in GitHub Desktop.
Save jbenner-radham/2a8721b1bf357b91fc66 to your computer and use it in GitHub Desktop.
Handlebars render to HTML task for Gulp.js, with a little bit of the Harp metadata context spec implemented. (using ES6 arrow functions and string templates)
'use strict';
var $ = require('gulp-load-plugins')();
var _ = require('lodash');
var fs = require('node-fs-extra');
var gulp = require('gulp');
var handlebars = require('handlebars');
var path = require('path');
gulp.task('handlebars', () => {
return gulp.src('*.hbs')
.pipe($.tap(file => {
var data = {};
var ext = path.extname(file.path);
var filename = file.path.replace(file.base, '');
var resource = path.basename(file.path, ext);
// According to the Node API using file exists methods are
// deprecated because they're anti-patterns so it's suggested to
// just attempt to open every file and wrap it in a try/catch.
try {
/**
* Parse metadata according to the Harp spec
* @see http://harpjs.com/docs/development/metadata
*/
data = fs.readJsonSync(`${file.base}_data.json`);
} catch (e) {}
var context = data.hasOwnProperty(resource) ? data[resource] : {};
try {
// Page specific metadata will overrule global data.
var metadataFile = $.util.replaceExtension(file.path, '.json');
_.merge(context, fs.readJsonSync(metadataFile));
} catch (e) {}
var html = handlebars.compile(file._contents.toString()).call(this, context);
file._contents = new Buffer(html);
file.path = $.util.replaceExtension(file.path, '.html');
}))
.pipe(gulp.dest('tmp/'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment