Client side templating Really ???

Some years back when the web applications were simple and straight forward i.e. upon receiving a request from the client, at server end, we do the data processing, DB operations and then make HTML files and then send back the response to the client. So even if when we want some part of the page to change then also we had to load the whole page again. But after AJAX came into picture this problem was fixed and we make AJAX call to get the required data and put it into the Web page. We also used Server side templating engines to separate the business logic from presentation. Then why do we need Client side templating engines. I will try to answer this question through my this blog. 🙂

Today the web applications are following dynamic interface and by dynamic interface I mean real time updates. For example lets say Facebook, when we scroll down we see a loader then after a while some more feeds appear on the news feed section, also when some new feeds comes up then it appears at the top of the news feed section. The magician here is AJAX but we can improve the magic trick by having client side templates. Previously we were using HTML for AJAX response but now we are getting a JSON response. By doing this we increase the performance as the request-response time decreases as JSON data is light weight than HTML. Then how did we get the HTML in the view. People previously used JavaScript for binding the data to view but now the trend has moved to client side templates. We create a template file and function that can be used to generate the HTML upon passing the JSON response. But when we can do this by JavaScript then why bother about templating. The answer is simple. Using Client side templates we can achieve the following

  • Cleaner and simpler code
  • Decoupled code
  • Code re-usability and maintainability.

Cleaner and simpler code is self explanatory. If we do the binding in JS then we have a JS file that looks ugly and confusing. Today we are following MVC architecture everywhere. The main idea behind this is to separate the models (Back end DB operations), with views and controllers (the connector of Models and Views, in short you can say the business logic). So why we don’t apply this to client side also. So decoupled code means that that you separate out the processing of data with the presentation. In general, leveraging templates is a great way to separate markup and logic in views, and to maximize code re-usability and maintainability. With a syntax close to the desired output (i.e. HTML), you have a clear and fast way to get things done. So let’s take a look at : client-side templating.

A template is “A document that contains parameters, identified by some special syntax, that are replaced by actual arguments by the template processing system.” From http://foldoc.org/template.

The syntax of the template depends on the template engine you want to use. This engine takes care of parsing the templates, and replacing the placeholders (variables, functions, loops, etc.) with the actual data it is provided. Some template engines are logic-less. This doesn’t mean you can only have simple placeholders in a template, but the features are pretty limited to some intelligent tags (i.e. array iteration, conditional rendering, etc.). Other engines are more feature-rich and extensible. Although each template engine has its own API, usually you will find methods such as render() and compile(). The render process is the creation of the end result by putting the actual data in the template. In other words, the placeholders are replaced with the actual data. And if there is any templating logic, it is executed. To compile a template means to parse it, and translate it into a JavaScript function. Any templating logic is translated into plain JavaScript, and data can be fed to the function, which concatenates all the bits and pieces together in an optimized way.

For this blog we will look at the Handlebars example. You can download Handlebars from its home site . Include the JS library of handlebars in your HTML snippet.   Lets say your Data is of the below format,

var data = {
     "title": "Story",
     "names": [
         {"name": "Tarzan"},
        {"name": "Jane"}
     ]
 }

You design your template like this.    

<h1>{{title}}</h1>
<ul>
    {{#names}}
        <li>{{name}}</li>
    {{/names}}
</ul>

Then in your AJAX success callback do this,

// Get the HTML of your template
var template = $('#myTemplate').html();
// Prepare the compiled template function
var compiledTemplate = Handlebars.compile(template);
// Pass the data to your compiled template function
var result = compiledTemplate(data); 

The result will contain this,

<h1>Story</h1>
<ul>
    <li>Tarzan</li>
    <li>Jane</li>
</ul>

On the next blog we will have look at how the processing is done and some more features of Handlebars.js. We will compare different client side templates. Happy Coding. 🙂

Advertisements

One thought on “Client side templating Really ???

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s