Of Templates and Caterpillars

A Template analogy

...by dave elkan

If data is a caterpillar

...and HTML is a butterfly

...then the template is the cocoon

Compiling Templates

A template's source (the silk)
<article>
    <h1>{{headline}}</h1>
    <p>{{bodyText}}</p>
</article>
...becomes Javascript! (the cocoon)
function article(params) {
    return "<article>" +
            "<h1>" + params.headline + "</h1>" +
            "<p>" + params.bodyText + "</p>" +
        "</article>";
}

And then they can be rendered

Data goes in. HTML comes out

Rendering Templates

A compiled template...
function article(params) {
    return "<article>" +
               "<h1>" + params.headline + "</h1>" +
               "<p>" + params.bodyText + "</p>" +
           "</article>";
}
given data...
article({
    headline: "Caterpillars revolt",
    bodyText: "Silk price skyrockets"
});
returns HTML
<article>
    <h1>Caterpillars revolt</h1>
    <p>Silk price skyrockets</p>
</article>

Templates are versatile

  • Compile and render them on the server
  • Send them to the browser (javascript file)
  • Render them in the browser
  • Best of both worlds
    • A dynamic 'single page' app
    • With SEO

Twitter s#!t

HTML5 History API

an ideal partnership

  • History API
  • +
  • Shared Templates

why is this better?

  • SEO (important, but not for everyone)
  • Performance
    • Deliver what the user asks for
    • HTML caching
    • Template caching (just a javascript file)
    • Minimise onDomReady ajax

twitterpillar

An example app

get Twitterpillar at

edave.net


follow me

@edave

Thank you

Caterpillar pictures copyright "The Very Hungry Caterpillar" by Eric Carle