public
Last active — forked from garth/Jakefile.js

Precompile .handlebars templates with node js

  • Download Gist
ember-precompile.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
var fs = require('fs');
var vm = require('vm');
 
var emberjs = fs.readFileSync('public/javascripts/vendor/ember-0.9.5.min.js', 'utf8');
var templatesDir = 'templates';
var destinationDir = 'public/javascripts/templates';
 
function compileHandlebarsTemplate(templatesDir, fileName) {
var file = templatesDir + '/' + fileName;
 
//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);
 
var namedTemplateJs = 'Ember.TEMPLATES["' + fileName.replace(/.handlebars/, '') + '"] = Handlebars.template(' + context.templatejs + ');';
 
//extract the compiled template from the vm context and save to .js file
fs.writeFileSync(file.replace(/\.handlebars$/, '.js').replace(templatesDir, destinationDir), namedTemplateJs, 'utf8');
}
 
console.log('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');

This version differs from the original in that:

  • it does not require jake
  • it adds all templates to the Ember.TEMPLATES object
  • it allows you to output the .js files to a different directory than the templates source

How can i precompile partials?

I don't think I've used handlebars partials, so I'm not sure, but I'd suspect this approach could be used to compile partials too.

Getting "TypeError: Cannot read property 'fixHooks' of undefined" with Ember 1.0.0RC5

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.