Created
September 5, 2012 19:53
jQuery Mustache Templating Function
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( $ ){ | |
$.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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: $("#finalContainer").mstch_tmpl($("#template"), {first_name:"Sergio", :last_name:"Campamá"})