Skip to content

Instantly share code, notes, and snippets.

@sergiocampama
Created September 5, 2012 19:53
Show Gist options
  • Save sergiocampama/3643500 to your computer and use it in GitHub Desktop.
Save sergiocampama/3643500 to your computer and use it in GitHub Desktop.
jQuery Mustache Templating Function
(function( $ ){
$.fn.mstch_tmpl = function(template, object) {
var that = this;
var template_string;
//Check if template is a string or a jQuert object
if (typeof(template)=='string' && isNaN(template)) {
template_string = template;
} else if (template instanceof jQuery){
template_string = template.html();
}
//Function to render the object in the template
var render = function(template_, object_) {
var output = Mustache.render(template_, object_);
that.append($(output));
}
//Check if object is an array, causing it to render all the objects in the array
if( Object.prototype.toString.call( object ) === '[object Array]' ) {
for (var i = 0; i < object.length; i++) {
render(template_string, object[i]);
};
} else {
render(template_string, object);
}
};
})(jQuery);
@sergiocampama
Copy link
Author

Usage: $("#finalContainer").mstch_tmpl($("#template"), {first_name:"Sergio", :last_name:"Campamá"})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment