Created
April 29, 2010 12:01
-
-
Save badsyntax/383501 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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