Skip to content

Instantly share code, notes, and snippets.

@ckniffen
Last active December 17, 2015 16:09
Show Gist options
  • Save ckniffen/5637233 to your computer and use it in GitHub Desktop.
Save ckniffen/5637233 to your computer and use it in GitHub Desktop.
Grunt Task to compile handlebar templates into static html files
module.exports = function(grunt) {
var handlebars = require('handlebars');
var path = require('path');
var registerPartials = function(partialsDir){
var partials = grunt.file.expand(partialsDir + '**/*.html');
partials.forEach(function(partial){
var partialName = partial.replace(partialsDir, '').replace(path.extname(partial), '');
handlebars.registerPartial(partialName, grunt.file.read(partial));
});
};
grunt.registerMultiTask('compile-html', 'Compile Handlebars templates ', function() {
var config = this.data;
registerPartials(config.partialsDir);
this.files.forEach(function(fileObj){
var compiledTemplate = handlebars.compile(grunt.file.read(fileObj.src[0]));
grunt.file.write(fileObj.dest, compiledTemplate(config.context));
});
});
};

#Example Usage

'compile-html': {
    tablet: {
        partialsDir: 'app/html/includes/',
        files: [{
            expand: true,
            cwd:'app/html',
            src: '*.html',
            dest: 'dist/html',
            ext: '.tablet.html'
        }],
        context: {
            isPhone: false,
            device: 'tablet'
        }
    },
    phone: {
        partialsDir: 'app/html/includes/',
        files: [{
            expand: true,
            cwd:'app/html',
            src: '*.html',
            dest: 'dist/html',
            ext: '.phone.html'
        }],
        context: {
            isPhone: true,
            device: 'phone'
        }
    }
}

#TODO:

  • Add Helper support
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment