Skip to content

Instantly share code, notes, and snippets.

@badsyntax
Created April 29, 2010 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badsyntax/383501 to your computer and use it in GitHub Desktop.
Save badsyntax/383501 to your computer and use it in GitHub Desktop.
// simple jQuery templating: replace placeholders in textnodes
// placeholder format: ${a-z}
// usage $(elem).render({ dataKey: dataValue });
// demo: http://badsyntax.github.com/jquery-templating.html
$.fn.render = function(data){
data = data || {};
function walkTextNodes(textNodeCallback){
(this.nodeType === 3 && textNodeCallback) && textNodeCallback.call(this);
$.each(this.childNodes, function(){
walkTextNodes.call(this, textNodeCallback);
});
}
function replace(key){
this.nodeValue = this.nodeValue.replace(new RegExp('\\$\{' + key + '\}', 'g'), data[key]);
}
return this.each(function(){
walkTextNodes.call(this, function(){
var nodeValue = this.nodeValue.replace(new RegExp('\\n', 'g'), '');
while(match = /\{(.*?)\}/g.exec(nodeValue))
(data[match[1]]) && replace.call(this, match[1]);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment