Created
August 28, 2011 11:35
-
-
Save n0nick/1176566 to your computer and use it in GitHub Desktop.
Quick jQuery plugin to load a Handlebars template into an element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function($) { | |
$.stacheComb = function(el, name, context, options) { | |
var defaults = { | |
container: 'body', | |
path : 'templates/' | |
}; | |
var plugin = this; | |
plugin.settings = {}; | |
var init = function() { | |
plugin.settings = $.extend({}, defaults, options); | |
plugin.el = el; | |
plugin.name = name; | |
$.when(plugin.loadTemplateSource()) | |
.then(function(source) { | |
var template = Handlebars.compile(source); | |
$(plugin.el).html(template(context)); | |
}); | |
}; | |
plugin.loadTemplateSource = function() { | |
var settings = plugin.settings, | |
$template = $('script[data-template="'+plugin.name+'"]', | |
settings.container); | |
if ($template.length) { | |
// get template source from a script element | |
return $template.html(); | |
} else { | |
// get template source from external file | |
return $.get(settings.path + plugin.name) | |
.then(function(data) { | |
// store code into script element, for the future | |
$template = $('<script/>', { | |
'type': 'text/x-handlebars-template', | |
'data-template': plugin.name | |
}).html(data); | |
$template.appendTo(settings.container); | |
}) | |
.promise(); | |
} | |
}; | |
init(); | |
}; | |
$.fn.stacheComb = function(name, context, options) { | |
var plugin = new $.stacheComb($(this), name, context, options); | |
return $(this); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment