The Handlebars JavaScript library provides us with a templates system we can use to create new strings for various purposes, such as new source code and configuration files. Templates created using the Mustache.js JavaScript library are compatible with Handlebars. We can use the same templates with both libraries.
The following code sample shows how simple it is to create a new template using the Handlebars.js JavaScript library.
<!DOCTYPE html> <html> <head> <title>handlebars.js demo</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script type="text/javascript" src="handlebars.js"></script> </head> <body> <div id="contentplaceholder"></div> <script id="mytemplate" type="text/x-handlebars-template"> <div class="main"> <h1>{{title}}</h1> <div class="secondary"> {{body}} </div> </div> </script> <script type="text/javascript"> var str = $("#mytemplate").html(); var template = Handlebars.compile(str); var data = {title:"javascript is awesome!",body:"we all lova coding and especially for the web!"}; $("#contentplaceholder").html(template(data)); </script> </body> </html>
The following video clip overviews this code sample, shows its execution and explains each and every part of it.
You can find more video clips, code samples and training materials for learning how to use this new JavaScript library in my Handlebars.js Basics new course at abelski.lifemichael.com.