Skip to content

Instantly share code, notes, and snippets.

@prettycode
Last active December 16, 2015 06:49
Show Gist options
  • Save prettycode/5393948 to your computer and use it in GitHub Desktop.
Save prettycode/5393948 to your computer and use it in GitHub Desktop.
Generate HTML from JavaScript object literals.
<!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: '&copy;' + 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