Tuesday, October 29, 2013

Templating with KnockoutJS

Another nice feature of KnockoutJS is the ability to have templates to display your data. For instance, say that if you have a collection of data and you want them to be displayed in a particular format without having to do much DOM manipulation. This can be achieved in two ways when it comes to KnockoutJS;


  • Using jQuery based templating
  • Using native knockout templating
In this tutorial i will show you both the ways and you will see why you would always want to use the native KnockoutJS templating given its unobtrusive nature.

So first off let us look at the example below;


 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <title>Superhero Registration</title>
</head>

<body>

 <div data-bind="template:'superHeroTemplate'">
  
  
 </div>


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="jquery-tmpl.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>

 <script type="text/javascript">
 
 $(function(){
   
   var data = [
    new superHero('Superman'),
    new superHero('Spiderman')
   ];
   
   var viewModel = {
    superHeroes:ko.observableArray(data)
   };
   
   function superHero(name){
    return {
     name:ko.observable(name)
    };
   }
   
   ko.applyBindings(viewModel);
  }
  );
 </script>
<script id="superHeroTemplate" type="text/html">
 <ul>
  {{each superHeroes}} 
   <li>${name}</li>
  {{/each}}
  
 </ul>
</script>
</body>
</html>

Ok i am obsessed with superheroes hence the use of examples follow the same pattern. Here what i am doing is constructing an observable array of super heroes.


 
function superHero(name){
    return {
     name:ko.observable(name)
    };
   }

The above function wraps the passed in input parameter to an observable object and passes it back. This is not required, but i have done as such so that Knockout will manage not only the observable array, but also the elements within the array since these are now observable objects themselves.

Here i am using jQuery templating and as such you need one additional script file to be included which you can dowload from here. Then you need to include it on your path in order for this example to work. I have saved this script file as jquery-tmpl.js. Note that the order you include these scripts are important as well. First it should be the jQuery script, then the jQuery template script and finally the KnockoutJS script.

First in the root element we need to define the template we are going to use. This is done as follows;


 
<div data-bind="template:'superHeroTemplate'">

Here you can see in the data-bind attribute i have defined the template as superHeroTemplate. Now this name is the name i have used as the id attribute within the template script i have used below;


 
<script id="superHeroTemplate" type="text/html">
 <ul>
  {{each superHeroes}} 
   <li>${name}</li>
  {{/each}}
  
 </ul>
</script>

Note that i have specified the type as text/html here since i do not want the browser to interpret this script tag since we are using this for the sole purpose of templating. The superHeroes attribute i have defined within the each tag is the name in my viewModel which is shown below. Also the ${name} attribute is what i am returning from the superHero function that returns obserable objects when passed in the name of the super hero.


 
 var viewModel = {
    superHeroes:ko.observableArray(data)
   };

This is all that is required for this to work. One thing you might have noticed is that this is a bit too obtrusive in terms of using additional DOM and script tags to make this work. This looks more of a hack since we are specifying script tags with a type calls text/html which is not valid just to make the templating work. This is where the native Knockout templating comes in handy. Let us look at how you can do the same using that and you will see why that is much cleaner.



 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <title>Superhero Registration</title>
</head>

<body>

 <div>
  <ul>
   <!-- ko foreach:superHeroes -->
    <li data-bind="text: $data.name"></li>
   <!--/ko-->
  </ul>
  
 </div>


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="jquery-tmpl.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script>

 <script type="text/javascript">
 
 $(function(){
   
   var data = [
    new superHero('Superman'),
    new superHero('Spiderman')
   ];
   
   var viewModel = {
    superHeroes:ko.observableArray(data)
   };
   
   function superHero(name){
    return {
     name:ko.observable(name)
    };
   }
   
   ko.applyBindings(viewModel);
  }
  );
 </script>

</body>
</html>

As you can see, no script tags were used. You directly work on the DOM and only need to add HTML comments block and write your code within that. You can even get rid of writing it within comments and directly embed the foreach loop within the DOM element as follows;


 
<div>
  <ul data-bind="foreach:superHeroes">
   <li data-bind="text:$data.name"></li>
  </ul>
  
 </div>

Much cleaner isnt it? No more hacks, just direct DOM manipulation. That is the power this library gives you. You can write it according to what you prefer.

So that ends my article on how to use templating with KnockoutJS. If you have any queries or feedback, please do leave by a comment which is as always highly appreciated.

Have a nice day everyone!!