Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Template Manager plugin for Loading HBS template files:
/*
templateManager - Async Handlebars template loader/cacher.
@author Mohan Dere
@version 1.0
@requires jQuery || zepto, underscore, Handlebars.js
*/
(function() {
window.TemplateManager = (function() {
var cache, defaults, fetchAndCache;
defaults = {
path: '/tpl/',
ext: '.hbs'
};
cache = {};
function TemplateManager(options) {
this.options = options != null ? options : {};
_.defaults(this.options, defaults);
if (this.options.cache) {
cache = this.options.cache;
}
}
TemplateManager.prototype.load = function(tpl, callback) {
if (_.has(cache, tpl)) {
return callback(cache[tpl]);
}
tpl = fetchAndCache.apply(this, arguments);
if (!callback) {
return tpl;
}
return tpl.done(function(tplString) {
if (callback) {
return callback(tplString);
}
});
};
fetchAndCache = function(tpl) {
var deferred, tplPath,
_this = this;
deferred = new jQuery.Deferred();
tplPath = "" + this.options.path + tpl + this.options.ext;
jQuery.ajax({
url: tplPath,
type: 'GET',
dataType: 'text',
success: function(tplString) {
cache[tpl] = Handlebars.compile(tplString)
cache[tpl].tplString = tplString;
return deferred.resolve(cache[tpl]);
}
});
return deferred;
};
return TemplateManager;
})();
}).call(this);
Usage:
// Create the WordPress Backbone namespace.
var jwfpApp = {
_views: {},
_models: {},
_collections: {},
_vent: _.clone(Backbone.Events),
tpl: new TemplateManager({
path: jwfpAppData.tpl_path
})
};
// Inside view file and in render function
var self = this;
jwfpApp.tpl.load('tpl/homePageunction(template) {
self.$stageConatiner.html(template({});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.