Skip to content

Instantly share code, notes, and snippets.

@karolk
Created March 26, 2012 13:53
Show Gist options
  • Save karolk/2205189 to your computer and use it in GitHub Desktop.
Save karolk/2205189 to your computer and use it in GitHub Desktop.
Templating plugin for jQuery working with HTML tree. No <% fancy %> {% brackets %}
$.fn.temple = function(stash) {
var rootNode = this,
childNodes = rootNode.find('[data-templ]'),
stencil;
for (var propName in stash) {
if ( $.isArray(stash[propName]) ) {
var stashArray = stash[propName];
var $node = childNodes.filter('[data-templ="'+propName+'"]'),
isCollectionNode = $node.is('ol, ul, dl, table');
if ($node.length && isCollectionNode) {
stencil = $node.children().eq(0);
if (stencil.length) {
stencil = stencil.clone();
$node.empty();
}
stashArray.forEach(function(stashArrayElem) {
var $subNode = stencil.clone();
$subNode.temple(stashArrayElem)
$node.append($subNode);
})
}
}
else {
childNodes
.filter('[data-templ="'+propName+'"]')
.text(stash[propName])
}
}
return rootNode;
};
@karolk
Copy link
Author

karolk commented Mar 26, 2012

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