The Way of Client-Side Templating

templating.jpgIt is generally accepted that in every field of IT where a UI is needed there is great benefit from the separation between the content and the presentation rules. To quote Martin Fowler from his book “Patterns of Enterprise Application Architecture”: ”the separation of presentation from model is one of the most fundamental heuristics of good software design”. Especially in the area of web development this is somewhat of a holy grail, where every new framework or architecture claims that it has managed to split these two different considerations in a way so much better than everybody else.

So, how would you go about separating these Siamese twins? One of the usual ways people strive to achieve this is by trying to make the best of the MVC architectural pattern. It is common to split an application into separate layers: presentation (UI), domain logic, and data access. The MVC patterns that was originally intended for Smalltalk goes further by additionally separating the presentation layer into View and Controller. The View in particular renders the model into a form suitable for interaction, typically a user interface element.

The View layer classically implements a templating mechanism where content is assigned to a template and a template rendering engine performs the necessary transformations for the display. Although the use of a templating engine is not required, it has several benefits. First of all it provides a well-defined formalism for the effective separation between content and presentation. Also because the whole concept is based on a loosely-coupled relationship between engine and templates, it promotes reusability and ensures easier refactorings. Another important benefit is also the fact that it encourages the divisions of labor, where different people are assigned the user interface and others the domain logic.

It might not be clear to many developers, especially to younger ones, but the above reasons where the fundamental motive we came up with technologies like JSP, PHP and ASP. All these web development languages are basically template languages and where conceived in order to separate program logic from HTML markup. The first time I came in contact with this kind of languages was 9 years ago during the break from a Lotus Notes training and I can still remember how revolutionary JHTML looked for someone coming from the CGI world, like me.

In the case of web applications where the UI is the browser that renders the HTML, the dominant paradigm is for the templating component to exist server-side. In this post we are going to be dealing with the presentation logic that sits between the domain logic and the pure layout and design logic that is handled by CSS rules that manage colors, sizes, fonts and positions. Although you can do many things to manipulate the presentation with CSS its power is restricted due to the limitations of the CSS implementations and is beyond the scope of this article.

In the Java world the most popular templating solution is Tiles by the Apache Software Foundation. It allows authors to define page fragments which can be assembled into a complete page at runtime. These fragments, or tiles, can be used as simple includes in order to reduce the duplication of common page elements or embedded within other tiles to develop a series of reusable templates. These templates streamline the development of a consistent look and feel across an entire application. Tiles in conjunction with Struts have been the default solution for Java web developers for the last years.

On the other side of the river, in the PHP realm, Smarty has been the dominant templating framework, that provides the programmer and template designer with nice tools to automate tasks commonly dealt with at the presentation layer of an application. Another one is PHPTAL which implements the Zope Page Templates syntax. This is my personal favorite because it works on XML attributes instead of markup tags so you can use it to insert dummy content in places where for example you get data form a DB. In this way you can view your templates in a WYSIWYG editor like Dreamweaver. Although the implementation differs from Tiles, the basic pattern for all these engines is the same: do the templating server-side.

When talking about templating it is important to mention the Composite View pattern. This is one pattern that is commonly used by templating engines to assemble a web page from several components. To quote the Core J2EE Pattern’s Catalog: “Use composite views that are composed of multiple atomic subviews. Each component of the template may be included dynamically into the whole and the layout of the page may be managed independently of the content.” This functionality is quite common in portals where individual parts of a page are different components with diverse sources and caching settings that are assembled in a flat page (or hierarchies). The benefits of having pluggable and reusable components are obvious. The Composite View pattern is based on the GoF Composite pattern which composes objects into tree structures to represent part-whole hierarchies.

Although in the early days of the Web the browsers where just dumb markup renderers, with the emergence of Firefox 2 and IE 7 they have come to a point where the application developer can rely on the client side for several functions. JavaScript implementations still have many incompatibilities but you can count on them to perform many complex tasks as asynchronous access to remote resources (XHR) and generations of multifaceted markup. Also many frameworks like Dojo, jQuery and Prototype have emerged that assist the development of intricate OO applications that under the hood leverage patterns and best practices. Finally the browsers pack several other components that are exposed through simple APIs like their XSLT engines.

All the above reasons are strong enough to make us consider moving a greater part of our application to the client-side. Since the presentation logic is the closest layer, it comes natural to reflect on if it would be reasonable to move it to the browser and also the various ways that this could be achieved.

Having the presentation – templating logic in the client-side has several great benefits:

First of all you get the ultimate division of labour since the presentation is not only in a different language/technology than the rest of your application but it is not even located in the server. The people responsible for it might not even have access to the server.

The high degree of separation that is innate of this paradigm has the result of producing highly decoupled architectures. Besides the flexibility that the decoupling brings, it is obvious that it promotes testability and makes for easier refactorings.

Since the various components will be downloaded in the form of XML, JSON, YAML and will be assembled at the client-side (for example in the manner of Composite View Patterns) we can benefit from the various network caching mechanisms. Our “content components“ may be cached by proxies or even at the browsers. Imagine a portal page that consists of 10-12 different parts (components). When you visit another page most of them will not change and are already in your cache. In this way you save bandwidth both for the client and the server since for a busy portal the bandwidth cost per byte is a significant factor. Hell, with smaller network traffic you can even save the planet!

Another advantage would be that by distributing the template processing functionality to the clients you improve the scalability especially in installations with elaborate templating mechanisms. Maybe the presentation layer is not the usual place where you need to optimize for resources like in the case of DB connections or the memory management, but the various aspects of templating, like markup transformations and caching consume an important amount of system resources. By putting the load to the client you can save not only in bandwidth, as we saw in the previous paragraph, but also in CPU, memory and disk space.

Client-side templating is not something new. Actually it has been described as the Browser-Side Templating pattern in the Ajax Patterns Catalog. Although it is not the dominant paradigm, I feel that as browsers mature in terms of JavaScript engines and XSLT processing, it has the potential to become ubiquitous. Maybe even a buzzword 🙂

When I originally planned on writing this post, I had in mind to write a little code to demonstrate the concepts. Unfortunately due to the verbosity of markup code, the limited nature of a blog post and the several approaches the you can choose from, I believe that I wouldn’t be doing justice to the whole concept by just giving out a couple of short examples. If you are interested I would suggested you visited the online demo of JST and checked out an example of browser-side XSLT.

JST and XSLT and several other technologies are tools that can be used to develop client-side templating functionality. These tools are powerful and flexible enough in order to be combined together in various ways to provide for different deployment strategies. For example you might find that your application may well benefit from using the Two Step View pattern which basically transforms content to markup not in a single step, but in two. Or you could use more steps if you have well-defined natural hierarchies in your domain model. Also you might find that your architecture calls for the use of the View Helper pattern for handling logic that is part of the application but it is too complex to fit in the actual template.

Whatever you choose, there are several factors to consider before moving to client-side templating. In most cases these disadvantages are not prohibiting. It is important though to have them in mind since they might become a problem in some corner-cases.

In particular:

  • Although the frameworks provide us with abstractions that are portable, nobody guarantees that they are 100% portable
  • Client-side
    frameworks tend to be harder to debug. It is especially difficult for developers
    that are accustomed to strongly-typed languages like Java or C#, to try to
    debug JavaScript.
  • XSL has its roots in DSSSL which in turn is a subset of Scheme which is a dialect of Lisp. Therefore, mastering this language for someone coming from a procedural or OO background is a slow and painful procedure (but very useful).
  • Companies like Sun or Microsoft still push for their traditional server-side templating solutions so there is no major support or tooling.

6 thoughts on “The Way of Client-Side Templating

  1. Besides jst or xslt on the client, pure ( looks interesting. Have you looked into it?
    I also think that client-side templating will facilitate the creation of custom views of an app by its visitors, which can then be shared. At the very least easier greasemonkey scripts (since the data format will be standard, eg. json, yaml, etc ).

  2. Hi,
    i’m working on a ajax-web-application for private pleasure in the moment. Your post is the first thing i have found concerning client-side templating. Is client-side-templating similiar or even equal to single-page-application, and something like a MVC-thing with the V on the side of the client and the rest on the serverside? I would like to use the EXTJS framework for the client side and the Zend-Framework for the server side and though just exchange json-data.
    Does that sound reasonable to you? Would be great to get a response of an expert concerning MVC delegation with client-side-templating.
    Thx in advance

  3. “Is client-side-templating similiar or even equal to single-page-application, and something like a MVC-thing with the V on the side of the client and the rest on the serverside?”

    I’ve been trying for a long time to write a follow up piece on how AJAX and solid client side frameworks like Dojo and jQuery blur the lines of MVC, but haven’t found the time.

    To answer your question, YES in client-side-templating a large percentage of V part of MVC is done on the client.

    “I would like to use the EXTJS framework for the client side and the Zend-Framework for the server side and though just exchange json-data.”

    Most contemporary frameworks where developed to do the “V” primarily on the server and thus are far from optimal. Since what you need is decoupled services that produce e.g. json, I would suggest using a small core functionality from any framework you choose. Especially in the case of PHP you might find that the PEAR libraries can take you a long way.

    Be warned though that doing a large part of the MVC on the client is “the road less traveled by”, but at the end “that will make all the difference” 🙂

  4. Thx for your answer,

    that helped me. I searched a while and didn’t find to much concerning client side templating. At least not in the in manner i’m interested in.

    Is there any reference(book, paper, article, blog,..) that you could recommend me for further reading. Even if my application tends to be small I just want to practice the right design and structure for …mmhmh ..well, not doing ad-hoc-kamikaze-programming.

    Thx again

  5. Johann, if you want to get your hands dirty with client-side-templating, there are some very helpful examples on the JST site which you can extend. If you want to get the full picture I’d suggest going through the following:

    Also it would be nice if you had the time to have a basic understanding of the Web Presentation Patterns of the EAA book ( or the J2EE patterns catalog. Both are classics, but are starting to show their age.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s