Question

In order to avoid writing JavaScript code that manually generates HTML for dynamic pages (which is not only ugly, but not DRY at all), and having simplicity and elegance in mind (as opposed to performance), what are the advantages of using string based templates on the client, such as Mustache.js or Handlebars.js, retrieving json data and templates separately, over using a REST API that retrieves server-side rendered pieces of html?

I was under the impression that client-side templating was the best approach to keep it simple on dynamic pages, but after using it a bit I'm finding that maintaining a page like that is somewhat complex, and its main advantages are better performance and bandwidth usage, which are not generally my primary goals.

Was it helpful?

Solution

I'm currently using Twitter's Hogan library and before that I was using the Trimpath library. I'm a true believer in client side templating; but they should not be abused. Here is a few arguments:

  1. Just like with server side templates, it helps distinguishing application logic from presentation. Instead of creating a hierarchy of DOM elements manually during run time, defining a template with HTML and rendering it with data from javascript create more readable and elegant code.

  2. I find it practical to have client side templates for repeating hierarchies such as twitter posts, blog entries, news articles, etc... The server only sends the JSON data, (through an AJAX call most of the time), and the data can immediately be bound to the template.

  3. Template engines I have used update innerHTML with the generated HTML string. This is said to be faster than DOM manipulation, but I have never run a benchmark myself.

  4. Desktop applications and RIAs can benefit much from client side templates. They can drive their interfaces without depending on a 3rd party solution.

  5. We can easily have server side templates and client side templates in our projects. They can work together very well. In web projects, I would not recommend we should port our templates to the client side and only send data from the server. For example, I use server side templates with INCLUDE statements to build the entire page. One template can include another template structure to build the interface. This is a complicated task for client side templates that will just create unnecessary code and overhead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top