Skip to content

Instantly share code, notes, and snippets.

@sebastiandeutsch
Created November 23, 2012 16:05
Show Gist options
  • Save sebastiandeutsch/4136265 to your computer and use it in GitHub Desktop.
Save sebastiandeutsch/4136265 to your computer and use it in GitHub Desktop.
hogan/mustache compile task for grunt
grunt.initConfig({
hogan: {
// desired target name
dev : {
// indicate you want to compile templates
compile : {
// wildcard of desired templates (glob syntax)
templates : "source/**/*.mustache",
processName: function(filename) {
return filename.replace(/source\//, "").replace(/\.jst\.mustache/, "");
},
// desired namespace in context e.g. window.JST
namespace: "JST",
// output destination
output : "tmp/templates.js"
}
}
}
}
...
grunt.registerMultiTask('hogan', 'Compiles mustache and hogan templates.', function() {
var fs = require('fs');
var path = require('path');
var globsync = require('glob-whatev');
var hogan = require('hogan.js');
var compile = this.data.compile;
var namespace = compile.namespace || "JST";
grunt.log.writeln('Compiling for target '+ this.target + ': ' + compile.templates);
templates = "(function() {\n"
templates += "this." + namespace + " = {};\n";
globsync.glob(this.data.compile.templates).forEach(function(filepath) {
template = fs.readFileSync(filepath, 'utf8');
var fn = hogan.compile(template, { asString: true });
templates += namespace + "[\"" + compile.processName(filepath) + "\"] = function(c,p,i){return new Hogan.Template(" + fn + ").render(c,p,i);};\n"
});
templates += "}).call(this);\n";
fs.writeFileSync(compile.output, templates, encoding='utf8')
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment