vhtml + htm conditional comments
by Jason Miller
HTML
<script src="https://unpkg.com/vhtml"></script>
<script src="https://unpkg.com/htm"></script>
JavaScript
// preprocess strings to turn conditional comments into Elements
function html(strings) {
arguments[0] = strings.map(s => s
.replace(/<!--(\[.*?\])>/g, '<-- if="$1">')
.replace(/<!/g, '</')
);
return htm.apply(tag, arguments);
}
// turn <-- if=""> elements into <CC> components
function tag(type) {
if (type == '--') arguments[0] = CC;
return vhtml.apply(null, arguments);
}
// conditional comment implementation
const CC = props => {
return vhtml(null, null, [
raw(`<!--${props.if}>`),
props.children,
raw(`<![endif]-->`)
]);
}
// in vhtml, Fragments can have innerHTML (don't ask)
const raw = html => vhtml(null, {
dangerouslySetInnerHTML: { __html: html }
});
// now we can use full conditional comments in HTM!
console.log(html`
<html>
<head>
<title>Test</title>
<!--[if mso]>
<style>
body {
margin: 10px;
}
</style>
<![endif]-->
<style>
body {
background: white;
}
</style>
</head>
<body>
<h1>Test Email</h1>
</body>
</html>
`);