Skip to content

Instantly share code, notes, and snippets.

@jmichalicek
Created October 27, 2012 00:54
Show Gist options
  • Save jmichalicek/3962510 to your computer and use it in GitHub Desktop.
Save jmichalicek/3962510 to your computer and use it in GitHub Desktop.
Handlebars.js ajax templates example from Djukebox
$(document).ready(function() {
// lots of other stuff in the full code
var compiled_templates = new Object();
var ALBUMLIST = 'album-list.js'; // real code has several more of these. It's the filename of a handlebars.js template
function getTemplateAjax(file) {
// downloads a handlebars.js template via ajax and sticks it into the cache object after compiling
var template; // this could really go down in the success function
return $.ajax({
url: "{{ STATIC_URL }}djukebox/js/templates/" + file, //ex. js/templates/mytemplate.handlebars
cache: true,
dataType: "text",
success: function(data) {
template = Handlebars.compile(data);
compiled_templates[file] = template;
},
});
}
function switchView(template, context, callback){
// takes the name of the template file, the context to pass into it, and an optional callback
// checks to make sure the compiled template is cached, otherwise uses jquery deferred to
// to download the template and compile it and then the function calls itself again.
if(template in compiled_templates) {
$('#content').html(compiled_templates[template](context));
if(typeof callback === 'function') {
// We may have things to do after the template has been injected into the page
// such as bind events to newly added elements. We only want to do this after injection
// and not when we had to reload the template as below, so we can't just call this function
// from inside .when() and use .then() to do the bindings.
callback();
}
} else {
$.when(getTemplateAjax(template, context)).then(function() {
switchView(template, context, callback);
});
}
}
// load in a new view by doing something like so
// someAjaxCall() may make a call to an API to get the data used
// for the template context, like Djukebox does, or just about anything
// which needs to happen first.
$.when(someAjaxCall()).then(function(data){
// now that we have data for the template context, swap in the new view
switchView(ALBUMLIST, data);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment