Skip to content

Instantly share code, notes, and snippets.

@saadtazi
Created September 27, 2013 01:29
Show Gist options
  • Save saadtazi/6723006 to your computer and use it in GitHub Desktop.
Save saadtazi/6723006 to your computer and use it in GitHub Desktop.
requireJS plugin that compiles mustache template. Templates are added and automatically registered in your compiled js file using r.js.
/*
* requirejs plugin that loads mustache templates from the baseUrl and registers it in can.view
* Optimize/compiles/minifies the templates when the requirejs optimizer is run
* usage:
* require([
..,
'mustl!path/to/mustache/tmp.mustache' // no need to add a var in callback function for your template
], function () {})
*/
define(['module', 'text'], function (module, text) {
var buildMap = []
, text = text
;
mustl = {
load: function (name, req, onLoad, config) {
// if contains ejs extension
text.get(req.toUrl(name), function(templateTxt) {
buildMap[name] = templateTxt;
if (config.isBuild) {
onLoad(null);
return;
} else {
req(['can/view/mustache'], function(can) {
var id = can.view.toId(name);
can.view.mustache(id, templateTxt);
onLoad(null);
});
}
});
},
// for the optimizer
// can be improved by passing the template.out string
// the problem: requiring 'can' causes a 'window is not defined' error at build time
write: function (pluginName, moduleName, write) {
if (moduleName in buildMap) {
var tplText = text.jsEscape(buildMap[moduleName]);
write("define('"+pluginName+"!"+moduleName+"', ['can', 'can/view/mustache'], function(can){ " + "\n"
+ " var id = can.view.toId('"+moduleName+"') " + "\n"
+ "; " + "\n"
+ " can.view.mustache(id, '" + tplText.replace("'", "\'") + "'); })");
} else {
console.log('should not be here!');
}
},
pluginBuilder: 'mustl'
};
return mustl;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment