Skip to content

Instantly share code, notes, and snippets.

@pmcfernandes
Last active February 28, 2022 22:55
Show Gist options
  • Save pmcfernandes/0082e045363d033d64f8 to your computer and use it in GitHub Desktop.
Save pmcfernandes/0082e045363d033d64f8 to your computer and use it in GitHub Desktop.
Handlebars jQuery plugin
/**
* Usage:
*
* $('#template').handlebars({
* data: {
* name: 'Pedro Fernandes',
* website: 'impedro.com',
* author: true
* },
* done: function(result) {
* $('#resultdiv').html(result);
* }
* });
*/
(function ($) {
$.fn.handlebars = function (options) {
var defaults = {
data: null,
done: function(result) {}
},
opts = {};
$.extend(opts, defaults, options);
return this.each(function() {
$this = $(this);
var tmpl = $this.html();
var d = "";
if (typeof options.data == 'string' || options.data instanceof String) {
d = JSON.parse(options.data);
} else {
d = options.data;
}
var c = Handlebars.compile(tmpl);
done(c(d));
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment