Skip to content

Instantly share code, notes, and snippets.

@tedpennings
Created July 17, 2011 19:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tedpennings/1087981 to your computer and use it in GitHub Desktop.
Save tedpennings/1087981 to your computer and use it in GitHub Desktop.
Render Handlebars templates from a server-side resource with caching to session storage
/*
* This decorates Handlebars.js with the ability to load
* templates from an external source, with light caching.
*
* To render a template, pass a closure that will receive the
* template as a function parameter, eg,
* T.render('template-name', function(t) {
* $('#somediv').html( t() );
* });
*/
var Template = function() {
this.cached = {};
this.hasSessionStorage = !!window.sessionStorage;
};
var T = new Template();
$.extend(Template.prototype, {
render: function(name, callback) {
if (T.isCached(name)) {
callback(T.getFromCache(name));
} else {
$.get(T.urlFor(name), function(raw) {
T.store(name, raw);
T.render(name, callback);
});
}
},
renderSync: function(name, callback) {
if (!T.isCached(name)) {
T.fetch(name);
}
T.render(name, callback);
},
prefetch: function(name) {
if (!T.isCached) {
$.get(T.urlFor(name), function(raw) {
T.store(name, raw);
});
}
},
fetch: function(name) {
// synchronous, for those times when you need it.
if (! T.isCached(name)) {
var raw = $.ajax({'url': T.urlFor(name), 'async': false}).responseText;
T.store(name, raw);
}
},
getFromCache: function(name) {
if (T.hasSessionStorage) {
var cached = window.sessionStorage.getItem("template-" + name);
if (!!cached) {
return Handlebars.compile(cached);
} else {
return cached;
}
} else {
return T.cached[name];
}
},
isCached: function(name) {
return !!this.getFromCache(name);
},
store: function(name, raw) {
if (T.hasSessionStorage) {
window.sessionStorage.setItem("template-" + name, raw);
} else {
T.cached[name] = Handlebars.compile(raw);
}
},
urlFor: function(name) {
return "/resources/templates/"+ name + ".handlebars";
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment