Skip to content

Instantly share code, notes, and snippets.

@thehydroimpulse
Forked from lancejpollard/ember-precompile.js
Created December 1, 2012 06:12
Show Gist options
  • Save thehydroimpulse/4180782 to your computer and use it in GitHub Desktop.
Save thehydroimpulse/4180782 to your computer and use it in GitHub Desktop.
Precompile .handlebars templates with node js
var fs = require('fs');
var vm = require('vm');
var emberjs = fs.readFileSync('path/to/ember.js', 'utf8');
var templatesDir = 'path/to/template/dir';
desc('Compile all .handlebars templates');
task({ 'handlebars': [] }, function () {
process.stdout.write('Compiling .handlebars templates');
var files = fs.readdirSync(templatesDir);
var i;
for (i = 0; i < files.length; i++) {
if (/\.handlebars$/.test(files[i])) {
compileHandlebarsTemplate(templatesDir + '/' + files[i]);
process.stdout.write('.');
}
}
console.log('done');
});
function compileHandlebarsTemplate(file) {
//dummy jQuery
var jQuery = function() { return jQuery; };
jQuery.ready = function() { return jQuery; };
jQuery.inArray = function() { return jQuery; };
jQuery.jquery = "1.7.1";
//dummy DOM element
var element = {
firstChild: function () { return element; },
innerHTML: function () { return element; }
};
var sandbox = {
// DOM
document: {
createRange: false,
createElement: function() { return element; }
},
// Console
console: console,
// jQuery
jQuery: jQuery,
$: jQuery,
// handlebars template to compile
template: fs.readFileSync(file, 'utf8'),
// compiled handlebars template
templatejs: null
};
// window
sandbox.window = sandbox;
// create a context for the vm using the sandbox data
var context = vm.createContext(sandbox);
// load Ember into the sandbox
vm.runInContext(emberjs, context, 'ember.js');
//compile the handlebars template inside the vm context
vm.runInContext('templatejs = Ember.Handlebars.precompile(template).toString();', context);
//extract the compiled template from the vm context and save to .js file
fs.writeFileSync(file.replace(/\.handlebars$/, '.js'), context.templatejs, 'utf8');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment