HTML5 Zone is brought to you in partnership with:

I currently work in the capacity of Software Engineer at a reputed company in Sri Lanka. I'm most keen in J2EE Technologies and love working with open source libraries which fit my project needs. Very interested in the NoSQL concept and experimenting with various products to find a good blend for our projects within the company. Part time freelancer. Avid contributor in the stackoverflow arena. Android is another area which I am looking at with very keen interest as I believe mobile development is the way forward. Dinuka is a DZone MVB and is not an employee of DZone and has posted 24 posts at DZone. You can read more from them at their website. View Full User Profile

Templating with Knockout.js

11.11.2013
| 4300 views |
  • submit to reddit

Another nice feature of Knockout.js is the ability to have templates to display your data. For instance, say that 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 Knockout.js"

  • Using jQuery-based templating
  • Using native knockout templating

In this tutorial, I will show you both methods, and you will see why you would always want to use the native Knockout.js 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 my examples follow the same pattern. Here I am  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've done it 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 that you download 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. This name is the name I have used as the id attribute in the template script 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 like more of a hack since we are specifying script tags with a type calls via 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 an HTML comments block and write your code within that. You can even get rid of writing it within comments and directly embed the 'for each' loop within the DOM element as follows;
<div>
  <ul data-bind="foreach:superHeroes">
   <li data-bind="text:$data.name"></li>
  </ul>
  
 </div>
Much cleaner isn't 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!!






Published at DZone with permission of Dinuka Arseculeratne, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)