Skip to content

Instantly share code, notes, and snippets.

@michaljemala
Created February 1, 2013 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaljemala/4692594 to your computer and use it in GitHub Desktop.
Save michaljemala/4692594 to your computer and use it in GitHub Desktop.
/**
* RequireJS mustache plugin
*
* usage:
* require(['ModuleA', 'mustache!myTemplate'], function (ModuleA, myTemplate) {
* var a = new ModuleA();
* var html = myTemplate({foo: 'bar'});
*
* $(a.el).html(html);
* });
*
* The module requires the use of html5shiv or similar if you want to work with HTML5 elements in IE < 9
*
* Build the AMD version of mustache from here: https://github.com/janl/mustache.js and register it with requirejs
*
* Configuration:
* var require = {
* ... curl configuration ...
* mustache: {
* rootUrl: '/js/templates'
* templateExtension: 'bar' // Default = 'template'
* }
* };
*/
(function (window) {
'use strict';
/*
* Actual plugin code
**/
var templateCache = {},
rendererCache = {};
define(['text', 'mustache'], function(text, mustache){
return {
templateCache: templateCache,
rendererCache: rendererCache,
'load': function (resourceId, require, callback, config) {
var split = resourceId.split('!'),
name = split[0],
rootUrl = (config.rootUrl || (config.baseUrl + '/templates/')).replace(/\/\//g, '/'),
ext = config.templateExtension || '.template',
fullName = rootUrl + name + ext;
if(!config.isBuild && rendererCache[name]){
callback(rendererCache[name]);
return;
} else {
// The text plugin knows how to load files in node, rhino, and the browser, so let it do the hard work
text.load(fullName, require, function(template){
if(!rendererCache[name]){
templateCache[name] = template;
rendererCache[name] = function(data, partials){
var html = mustache.to_html(templateCache[name], data, partials);
return $(html);
};
}
callback(rendererCache[name]);
}, config);
}
}
};
});
}(typeof window !== 'undefined' ? window : {}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment