Last active
December 16, 2015 06:49
-
-
Save prettycode/5393948 to your computer and use it in GitHub Desktop.
Generate HTML from JavaScript object literals.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Proof of Concept</title> | |
<script> | |
// TODO how should Arrays be handled? | |
// TODO strict mode (no '\n' or padding) to allow for significant whitespace (e.g. for <pre>, <textarea>) | |
var toHTML = function(value, name, indent) { | |
var pad = new Array((indent = indent || 0)).join(' '); | |
if (typeof value === 'object') { | |
value = Object.keys(value).map(function(key) { | |
return toHTML(value[key], key, indent + 1); | |
}).join(''); | |
} | |
if (typeof name === 'undefined') { | |
return value; | |
} | |
return pad + '<' + name + '>\n' + value + '\n' + pad + '</' + name + '>\n'; | |
}; | |
</script> | |
<script> | |
// TODO how to specify attribute for tag, such as 'class' for CSS? | |
var view = { | |
html: { | |
head: { | |
title: 'Proof of Concept', | |
style: 'footer div { color: #F0F0F0; font-size: 8px; }' | |
}, | |
body: { | |
header: {}, | |
section: { | |
h2: new Date().toString(), | |
article: 'It was a dark and stormy night...' | |
}, | |
footer: { | |
div: '©' + new Date().getFullYear() + ' prettycode.org' | |
} | |
} | |
} | |
}; | |
</script> | |
<script> | |
window.onload = function() { | |
document.getElementById('output').innerHTML = toHTML(view); | |
}; | |
</script> | |
<style> | |
body { | |
margin: 0; | |
padding: 0; | |
width: 100%; | |
} | |
textarea { | |
height: 480px; | |
width: inherit; | |
} | |
</style> | |
</head> | |
<body><textarea id="output"></textarea></body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment