Skip to content

Instantly share code, notes, and snippets.

@PaulKinlan
Last active September 12, 2018 08:02
Show Gist options
  • Save PaulKinlan/800cd4cc10e20af386ba0837675ca8de to your computer and use it in GitHub Desktop.
Save PaulKinlan/800cd4cc10e20af386ba0837675ca8de to your computer and use it in GitHub Desktop.
Simple Templating
const applyTemplate = (templateElement, data) => {
const element = templateElement.content.cloneNode(true);
const treeWalker = document.createTreeWalker(element, NodeFilter.SHOW_ELEMENT, () => NodeFilter.FILTER_ACCEPT);
while(treeWalker.nextNode()) {
const node = treeWalker.currentNode;
for(let bindAttr in node.dataset) {
let isBindableAttr = (bindAttr.indexOf('bind_') == 0) ? true : false;
if(isBindableAttr) {
let dataKeyString = node.dataset[bindAttr];
let dataKeys = dataKeyString.split("|");
let bindKey = bindAttr.substr(5);
for(let dataKey of dataKeys) {
if(dataKey in data && data[dataKey] !== "") {
node[bindKey] = data[dataKey];
break;
}
}
}
}
}
return element;
};
<template id='itemTemplate'>
<div class="item" data-bind_id='guid'>
<h3><span data-bind_inner-text='title'></span> (<a data-bind_href='link'>#</a>)</h3>
<div data-bind_inner-text='pubDate'></div>
</div>
</template>
@beaufortfrancois
Copy link

beaufortfrancois commented Jul 5, 2017

@PaulKinlan Nit!

-      let isBindableAttr = (bindAttr.indexOf('bind_') == 0) ? true : false;
+      let isBindableAttr = bindAttr.startsWith('bind_');

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