Why templates are just a special case of AJAX

I've been writing webapps with template languages for some time. Templates are a nice way to stay as close as possible to the original, static HTML. I've noticed that with Ajax in general, and jQuery in particular, one can get even closer to not modifying static HTML. I've also noticed that templating can and should be done on both the client and server.

There's a very nice Ajax architecture that basically dictates that you make a request against the server, retrieve meaningful data (rather than data embedded in presentation) as XML and then insert that data into the DOM. This is precisely how server-side templates work! The only difference is that the data is not serialized, and is generally some architecture specific form. For example, in Java the template data may be object graphs embedded in a HashMap.

A server-side template, then, could theoretically be replaced by an Ajax call, if the template worked on the client. For some years now, there's been XSLT support in all modern web clients, and XSLT can indeed be used as a templating language of sorts. However, XSLT is verbose, unwieldy, and therefore fails miserably in the only criterion that matters: does the architecture minimize the mutations you have to make to static HTML?

Actually, I think it would be a nifty thing to do client-side only templates, but for practical reasons I don't think such an architecture would fly (first, because some clients don't support meaningful programmatic execution of any sort, and second, because you'd have to take special care to avoid that initial loadind performance hit). Therefore one needs a solution that can execute in both places. XSLT can indeed work both server and client side, but as we've seen it's a less than optimal solution.

The approach I like is to use JavaScript for the templating language. Indeed, one codes the software as if it was client-side only Ajax, and then rely on runtime parameters to tell the server to exec that initial XHR on the server. This is made possible in a Java server by two pieces of technology, Rhino, and John Resig's env.js. It works, it's nice, and I'll write about it in more detail if there is interest.

No comments: