Hacker News new | ask | show | jobs
by MatthewPhillips 5106 days ago
Client side templates are a hack, presently speaking. They are inserted into a script tag in the head (usually), so if you are working a single page app you need to include every template for your entire site in the head of the document. It works, but man is it ugly.

Then you have to include some bulky library that parses these scripts and compiles them to a function that you'll use later. All this happens pretty fast, but not any faster than just using the DOM apis.

I can't find the link, but I believe there is a proposal to standardize client side templating, so hopefully that will make the process a bit cleaner.

3 comments

Something like this may unclutter the situation, just use xmlhttprequest to get the templates on demand:

    //synchronous
    body.innerHTML = render('blog.html',data)

    //asynchronous
    render('blog.html',data,body)

    render=function(url,data,obj){
        if url in cache: use cache
        var http = xmlhttprequest()
        http.get(url,obj?async:sync)
        http.onready: 
            parse data in html 
            if obj: obj.innerHTML = html
            else: return html
    }
There are work arounds. What we really need is an HTML standard for including templates on a page. Can't we reuse the <link> tag for that?

  <link href="mytemplate.mustache" rel="template" type="text/mustache" onload="showSnippet()" />
I like that, except that templates are used on demand, so onload would be useless. A better way would be to put an id on them and defer their load for when really needed.

    <link hef='blog.html' rel='template' id='myblog' defer>
But still, we don't want to load 50 templates at the same time if the app is big then use one or two in that session, that's why loading them on demand with httprequest might be a better solution.

*Besides, being static in nature they would be cached on the server and client for instant access.

I threw together this gist which does your suggestion: https://gist.github.com/2955953

Use like thus:

  var tmpl = document.getElementById('myblog').template;
Beautiful!
Ideally you would preprocess your assets server-side (e.g Jammit), so templates end up being just another script to load.

This is still ugly, in that debugging templates is an impossible pain the arse because there's no useful line information. On the plus side they're much easier to read than a chain of DOM manipulations.

It's arguable whether this is "better". I usually have to interact with the DOM programmatically anyway (attaching events, for example), so why not build the DOM in javascript as well?

I use eco templates (CoffeeScript in HTML) that do not need a library to be interpreted once they are preprocessed server side. You minify them and save them as a variable in your source. No clutter, works nicely.