Created
September 9, 2016 23:12
-
-
Save jasonwaters/45e98e94c63b5066185453b00c02fc30 to your computer and use it in GitHub Desktop.
Jason's Template Renderer
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
<!DOCTYPE html> | |
<html> | |
<head> | |
</head> | |
<body> | |
<div id="output"></div> | |
<hr/> | |
<form id="myForm"> | |
<input placeholder="Name…" type="text" id="myName"/> | |
<input placeholder="Number…" type="number" id="myNumber"/> | |
<button type="submit">Add</button> | |
</form> | |
<script type="text/javascript"> | |
function renderTemplate(template, data, targetElement) { | |
var valueHolder = /\{(.+)\}/; | |
function getTemplateName(str) { | |
var matches = valueHolder.exec(str); | |
if (matches) { | |
return matches[1]; | |
} | |
} | |
function render(data) { | |
while (targetElement.firstChild) { | |
targetElement.removeChild(targetElement.firstChild); | |
} | |
var parser = new DOMParser(); | |
var htmlTemplate = parser.parseFromString(template, "text/html"); | |
var root = htmlTemplate.body.children[0]; | |
for (var i = 0; i < root.children.length; i++) { | |
var child = root.children[i]; | |
if (child.dataset['each']) { | |
var key = child.dataset['each']; | |
if (proxy[key]) { | |
var values = proxy[key]; | |
var childTemplate = child.childNodes[0].innerHTML; | |
var tagName = child.childNodes[0].tagName; | |
child.removeChild(child.childNodes[0]); | |
for (var j = 0; j < values.length; j++) { | |
var el = document.createElement(tagName); | |
el.innerText = values[j][getTemplateName(childTemplate)]; | |
child.appendChild(el); | |
} | |
} | |
} | |
} | |
targetElement.appendChild(root); | |
} | |
var proxy = new Proxy(data, { | |
set: function (target, property, value, receiver) { | |
target[property] = value; | |
render(target); | |
return true; | |
} | |
}); | |
render(data); | |
return proxy; | |
} | |
var myTemplate = "<div><ul data-each='myList'><li>{name}</li></ul><ul data-each='myList'><li>{number}</li></ul></div>"; | |
var myData = { | |
myList: [ | |
{name: 'nic', number: 1}, | |
{name: 'jeremy', number: 10} | |
] | |
}; | |
myData = renderTemplate(myTemplate, myData, document.getElementById('output')); | |
document.getElementById('myForm').addEventListener('submit', function (evt) { | |
evt.preventDefault(); | |
evt.stopImmediatePropagation(); | |
var nameValue = this[0].value; | |
var numberValue = this[1].value; | |
this[0].value = ''; | |
this[1].value = ''; | |
var newList = [].concat(myData.myList); | |
newList.push({ | |
name: nameValue, | |
number: numberValue | |
}); | |
myData.myList = newList; | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment