Interactive proof of concept of tag literals in JS. Translates to DOM instantiations in this demo. Start typing proper html, yo! Or see
this blog post
for more information.
By Peter van der Zee, ©
pvdz.ee
, March 2012
Auto execute
Translate to DOM
var e = <div class="foo">Try this! ;)</div>; parseInt(<span>element</span>, 10); console.log(<div>{['dynamic',"content"].join(' ')}</div>); // this generates the output below ;) document.getElementById('out').innerHTML = ''; document.getElementById('out').appendChild( <div> <style scoped> /* you have to escape the opening curly in inline css... :( */ p \{ margin: 5px; font-family: Arial; } </style> <h1>Tag literal syntax in JS</h1> <p>Check out this tag literal demo :D</p> <p>It is parsing the custom JS syntax real-time. You can specify tags just like numbers, strings or regular expressions. Nesting is allowed, but only proper nesting...</p> <p>It converts the inline tags to an internal data structure, much like JSON. This html page contains a reviver that translates this structure to proper dynamic DOM.</p> <p>As you can see the translated source is very bloated, blame the DOM standard for that.</p> <p>Of course <a href="https://en.wikipedia.org/wiki/ECMAScript">ES</a> already defines something called <a href="https://en.wikipedia.org/wiki/ECMAScript_for_XML">E4X</a>. I don't think anybody uses it though. Too complicated to be attractive.</p> <p>I doubt this doohicky has any chance of replacing it but I still wanted to throw this out there. Been playing in my head for over a year now. Finally got around to implement it. Only took me half a day too! Parsing <b>is</b> fun :D</p> <p>Please note that this is not a HTML parser, it's slightly stricter than that. The major difference is that it simply scans for tags. It requires unary tags to have the <i>xml-like</i> unary suffix (meaning <code>/\></code>).</p> <p>Other than that, open tags must be closed, one root tag per literal (although you could easily add syntax to support a node-list in case of multiple subsequent tag iterals...)</p> <p>Dynamic content is to be put between curly braces \{ \}. You can escape characters with a backslash \\. Unfortunately this also means that for inline css, you MUST escape the leading \{ for any declaration.</p> <p>Oh well, have fun there. Please report any feedback, bugs or feature requests to <a href="https://twitter.com/kuvos">me</a>! :)</p> <p>Contents is saved in and loaded from <code>localStorage</code>...D</p> </div> );
Out: