Skip to content

Instantly share code, notes, and snippets.

@mohandere
Created October 18, 2016 17:39
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 mohandere/845693ae20a37735f23a6d9be8e66e4f to your computer and use it in GitHub Desktop.
Save mohandere/845693ae20a37735f23a6d9be8e66e4f to your computer and use it in GitHub Desktop.
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