Skip to content

Instantly share code, notes, and snippets.

@there4
Forked from joefitzgerald/gist:1990736
Created May 23, 2012 22:48
Show Gist options
  • Save there4/2778321 to your computer and use it in GitHub Desktop.
Save there4/2778321 to your computer and use it in GitHub Desktop.
Handlebars JST Grunt Task
/*
* Grunt Task File
* ---------------
*
* Task: JST-HB
* Description: Compile handlebars templates to JST file.
* Dependencies: [email protected]
*
*/
task.registerBasicTask("jsthb",
"Compile handlebars templates to JST file", function(data, name) {
// If namespace is specified use that, otherwise fallback
var namespace = config("options.jst.namespace") || "JST";
// If template settings are available use those
var templateSettings = config("options.jst.templateSettings") || null;
// Expand files to full paths
var files = file.expand(data);
// Create JST file.
file.write(name, task.helper("jsthb", files, namespace, templateSettings));
// Fail task if errors were logged.
if (task.hadErrors()) { return false; }
// Otherwise, print a success message.
log.writeln("File \"" + name + "\" created.");
});
task.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