LnL7

DOM templating

There has been an explosion of templating languages, from the basic erb which just adds <% ... %> and <%= ... %> tags, to CofferKup that allows you to write your HTML markup in plain CoffeeScript.

However none of these make much sense to be used on the client. Why would we want JavaScript to parse HTML strings if we can directly interact with the DOM?


Implementation in CoffeeScript:

genDOM = (json) ->
  {elem, attr, body} = json
  node = document.createElement elem or 'div'

  if attr?
    for k,v of attr
      node.setAttribute k,v

  switch body?.constructor
    when String
      node.appendChild document.createTextNode body

    when Object
      node.appendChild genDOM body

    when Array
      for c in body
        node.appendChild genDOM c

  node

Example JSON data:

{
  "attr": {
    "id": "content"
  },
  "body": [
    {
      "elem": "header",
      "body": [
        {
          "elem": "img",
          "attr": {
            "src": "/img/aenean_vulputate.png",
            "style": "width:100%;"
          }
        }, {
          "elem": "h1",
          "body": "Nunc orci metus"
        }
      ]
    }, {
      "elem": "article",
      "body": "Integer est mauris, sagittis nec congue ut, luctus nec sapien. Curabitur commodo, orci eget cursus."
    }, {
      "elem": "article",
      "body": "Curabitur fringilla nunc quis dolor aliquam quis iaculis sapien auctor. Aliquam non arcu urna. Quisque."
    }
  ]
}

This will generate this DOM structure:

<div id="content">
  <header>
    <img src="/img/aenean_vulputate.png" style:"width:100%;" />
    <h1>Nunc orci metus</h1>
  </header>
  <article>
    Integer est mauris, sagittis nec congue ut, luctus nec sapien. Curabitur commodo, orci eget cursus.
  </article>
  <article>
    Curabitur fringilla nunc quis dolor aliquam quis iaculis sapien auctor. Aliquam non arcu urna. Quisque.
  </article>
</div>