Skip to content

Instantly share code, notes, and snippets.

@jwpage
Created July 16, 2012 23:39
Show Gist options
  • Save jwpage/3125864 to your computer and use it in GitHub Desktop.
Save jwpage/3125864 to your computer and use it in GitHub Desktop.
Precompile ember handlebars templates with gruntjs
/*
Adapted from: https://gist.github.com/2013669
Usage:
grunt.initConfig({
ember: {
all: {
src: 'templates/*.hjs',
dest: '../build/templates.compiled.js',
ember: 'path/to/ember.js',
handlebars: 'path/to/handlebars.js',
extension: 'hjs' // the extension of your handlebars templates
}
}
});
*/
var compileEmberTemplate = function (ember, handlebars, extension, input) {
var vm = require('vm');
var fs = require('fs');
var path = require('path');
var jQuery = function() { return jQuery; };
jQuery.ready = function() { return jQuery; };
jQuery.inArray = function() { return jQuery; };
jQuery.jquery = '1.7.1';
var element = {
firstChild: function() { return element; },
innerHTML: function() { return element; }
};
var sandbox = {
document: {
createRange: false,
createElement: function() { return element; }
},
console: console,
jQuery: jQuery,
$: jQuery,
template: fs.readFileSync(input, 'utf8'),
templatejs: null
};
sandbox.window = sandbox;
var context = vm.createContext(sandbox);
vm.runInContext(handlebars, context, 'handlebars.js');
vm.runInContext(ember, context, 'ember.js');
vm.runInContext('templatejs = Ember.Handlebars.precompile(template).toString();', context);
var namedTemplateJs = 'Ember.TEMPLATES["'+path.basename(input, '.'+extension)+'"] = Handlebars.template('+context.templatejs+');';
return namedTemplateJs;
};
grunt.registerMultiTask('ember', 'Precompile ember templates', function() {
var fs = require('fs');
var emberjs = fs.readFileSync(this.data.ember, 'utf8');
var handlebars = fs.readFileSync(this.data.handlebars, 'utf8');
var template_files = grunt.file.expand(this.data.src);
var output = '';
var ext = this.data.extension || 'handlebars';
template_files.forEach(function(template) {
output += compileEmberTemplate(emberjs, handlebars, ext, template);
});
grunt.file.write(this.data.dest, output);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment