Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
KnockoutJS Web Development

You're reading from  KnockoutJS Web Development

Product type Book
Published in Feb 2015
Publisher
ISBN-13 9781782161028
Pages 178 pages
Edition 1st Edition
Languages

Chapter 5. The Joy of Templates

A quick walk through history tells the story of how server-side code turned templates into magic. Data mixed with these templates and returned meaningful HTML for the client. These templates dynamically adapted to produce flexible and functional custom HTML pages. Along came AJAX and robbed the developer of this powerful approach to coding. But wait, templates are back again! Now they run at the client side. This chapter will teach you how to create the magic at the client side with Knockout. In this chapter, we will focus on:

  • Native templates

  • Enhanced collection handling

  • Render events

  • Third-party templates

  • Awesome template options

Knockout is not just about two-way binding. Done right, it is about more elegant and sustainable code. We will learn how to come around for another layer of making our page creation simpler as we learn to use the power of templating in KnockoutJS.

Native templates


Templates are patterns for how we merge data and the stuff the data fits into. The most popular form of templates on computers in the early days was something we called a mail merge. Programs like Microsoft Word would use a mail merge document and a data file, and merge them together. The original purpose was for printing.

Over the time, we shifted to using this same type of technology to do web pages. When a user would go to a website and request a web page, the servers started getting smarter. The data was mixed into a template and the merged result was returned to the browser as HTML. This was an amazing game changer for shopping sites and other sites where the basic page was the same. This is why we call these pieces of code templates.

One way to look at this is to think about when people decorate houses. We have things we call stencils. While the stencil defines how the shape of the result will look, it does not control what color you paint something with. If you have...

Enhanced collection handling


In our first segment, native templates, we focused on single sets of data. In JavaScript, we often have collections of data stored in arrays. We will be including an example here to show how to use templates stored in arrays.

We can copy the data from our last example page to this page. We will be using more of the structure this time around. We will start by focusing on the speakers. This array contains structured items for each speaker. The code section of our script tag should look like this:

vm = ko.mapping.fromJS(mySeminar);
ko.applyBindings( vm );

If you think this looks basically the same as the last example of code, you are right. It will change soon, but we are looking to make a point here. Arrays and non-arrays are not coded differently for routine binding functionality. Here is the segment of data that we will be using for this part of the exercise:

speakers : [
  { id: 1, name: "John Doe", bio: 'This is the bio for John.',
    skills: [ "jQuery","KnockoutJS...

Render event handling


One of the things you grow to appreciate as your experience grows is the ability to do event handling. I have not needed this functionality yet with Knockout code in the live sites we have built; but it is awesome to know it is there if we do need it.

We will be using the following code this time. We will use a different data set for this example to keep our code simpler and focus on just this section:

<script>
    var ViewModel = function(){
        seasons = ko.observableArray([
            { name: 'Spring', months: [ 'March', 'April', 'May' ] },
            { name: 'Summer', months: [ 'June', 'July', 'August' ] },
            { name: 'Autumn', months: [ 'September', 'October', 'November' ] },
            { name: 'Winter', months: [ 'December', 'January', 'February' ] }
        ]);
    showRendered = function(e){
      $(e).wrapInner("<em style='color:green'></em>");
    };
    };
  vm = new ViewModel();
    ko.applyBindings(vm);
</script>

This...

Third-party template options


There was a time when jQuery was exploring creating its own templates, but that effort did not mature to a full release. So we will not cover that template here. The most popular template used with Knockout seems to have been Underscore as a result. Personally, before jumping into Knockout my template of choice was, well is, Handlebars. Yet, I have enjoyed Knockout templates so much that it has never compelled me to go as far as integrating Handlebars with Knockout yet.

I have played around with Underscore just to get a taste of why others use Underscore with Knockout; to see if I was missing something. It came down to a developer style difference that some developers like to use the Underscore style of template coding and others prefer to use native Knockout templates. In this section, we will be honoring the Underscore fans' approach.

We suggest some copy and paste from the done directory of the example code for this to prevent typos. If you are awesome enough...

Awesome template options


There is one more time someone may want to do something with templates different from the pure native style of using templates with Knockout. This is because you may like to use a slightly different kind of coding style. In this last section of the chapter, we will give you a few more options.

We are back to native templates; I thought we should mention that in case someone had a question. Here are the templates that we will be using on this page:

<script type="text/html" id="guest-template">
    <h3>{{name}}</h3>
    <p>Seating: {{seating}}</p>
</script>
<script type="text/html" id="guest-template-alt">
    <h3>Others</h3>
    <p>Seating: General Seating</p>
</script>
<script type="text/html" id="tmpl-Seminar">
  <h3>{{name}}</h3>
  <p>Theme: {{byLine}}</p>
</script>

We will be using the data that we used from the beginning of the chapter with this example. Other...

Summary


This chapter has given you a well-rounded introduction to Knockout templates. If you have never used templates before, we hope you appreciate the concept of templates. If you have used them before, we hope you like the richer data-bound auto-updating ability of templates using Knockout.

In this chapter we have learned what templates do and how to use them with Knockout. We have learned how to nest templates with collections and non-collection structures. We have learned how to use event triggers and mixed a little jQuery in to modify template results. We have also learned how to mix in third-party template technology, the concept of subscribing to observables, and a couple of extra ways to merge templates onto our page. We also learned to use an alternative style of binding with the Punches library.

In our next chapter, we will dive into the wonder of building our own custom HTML tags. Has there ever been a time when you thought that standard HTML tags were limited? You actually wanted...

lock icon The rest of the chapter is locked
You have been reading a chapter from
KnockoutJS Web Development
Published in: Feb 2015 Publisher: ISBN-13: 9781782161028
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}