Skip to content

Instantly share code, notes, and snippets.

@mheap
Created May 20, 2012 20:52
Show Gist options
  • Save mheap/2759491 to your computer and use it in GitHub Desktop.
Save mheap/2759491 to your computer and use it in GitHub Desktop.
JST Handlebars templates

I really struggled to get this working. I initially found https://gist.github.com/1990736 but it wasn't working for me, so I decided to throw it out, copy the original JST task and adapt it.

The jsthb helper has been lifted entirely from https://gist.github.com/1990736, the rest I've hacked at myself. This has been tested with both ajax loading and a release build.

fetchTemplate: function(path, done) {
var JST = window.JST = window.JST || {};
var def = new $.Deferred();
// Should be an instant synchronous way of getting the template, if it
// exists in the JST object.
if (JST[path]) {
if (_.isFunction(done)) {
done(JST[path]);
}
return def.resolve(JST[path]);
}
// Fetch it asynchronously if not available from JST, ensure that
// template requests are never cached and prevent global ajax event
// handlers from firing.
$.ajax({
url: path,
type: "get",
dataType: "text",
cache: false,
global: false,
success: function(contents) {
JST[path] = Handlebars.compile(contents);
// Set the global JST cache and return the template
if (_.isFunction(done)) {
done(JST[path]);
}
// Resolve the template deferred
def.resolve(JST[path]);
}
}
/*
*
* Task: jsthb
* Description: Compile Handlebars templates to JST file
* Contributor(s): @mheap
*
*/
module.exports = function(grunt) {
var file = grunt.file,
log = grunt.log;
var _ = grunt.utils._;
grunt.registerMultiTask("jsthb",
"Compile underscore templates to JST file", function() {
var options = grunt.config("jsthb", this),
namespace = options.namespace || "JST",
settings = options.templateSettings || null,
files = file.expand(this.data);
// Create JST file.
file.write(this.target, grunt.helper("jsthb", files, namespace, settings));
// Fail task if errors were logged.
if (grunt.errors) { return false; }
// Otherwise, print a success message.
log.writeln("File \"" + this.target + "\" created.");
});
grunt.registerHelper("jsthb", function(files, namespace, templateSettings) {
// Ensure we get the underscore from the node_modules folder
var Handlebars = require("handlebars");
// Comes out looking like this["JST"] = this["JST"] || {};
var contents = "(function() {\n var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};\n";
// Compile the template and get the function source
contents += files ? files.map(function(filepath) {
var templateFunction = 'templates[\'' + filepath + '\'] = template(' + Handlebars.precompile(file.read(filepath)) + ');\n';
return templateFunction;
}).join("\n\n") : "";
return contents + "})();";
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment