Dynamic HTML Using Handlebars JavaScript

The concept of DHTML was Introduced in 1997 by Microsoft with the launch of Internet Explorer 4 to create interactive Websites with the combinations of multiple technologies i.e. HTML, JavaScript, CSS and later Server side technologies.

The main reason for dynamic HTML was to introduce re-usability of the code for data bound Web content; i.e., when using data in lists, tables etc. that requires a large amount of data to be displayed but with similar styling or visual format. Not only this, is was to induce more user interactivity e.g. displaying customize messages into a customized HTML message box instead of just displaying typical alerts during the system response for every user action. These requirements for the modern state of the art Websites with more user friendliness and user interactivity in play requires more versatile techniques from the front-end side.

Before I jump into what handlebars JavaScript is all about, let me share some of the examples of usage of dynamic HTML.


  1. <html>  
  2.   
  3. <head>  
  4.     <title>Dynamic Styles</title>  
  5.     <script language="JavaScript">  
  6.         function doChanges(e) {  
  7.             e.style.color = "green";  
  8.             e.style.fontSize = "20px";  
  9.         }  
  10.     </script>  
  11. </head>  
  12.   
  13. <body>  
  14.     <h3 onmouseover="doChanges(this)" style="color:black;font-size:18px">Welcome to Dynamic HTML!</h3>  
  15. </body>  
  16.   
  17. </html>  
The sample snippet given above will change the color of the text to green and change the font size of the text when a mouse cursor will move over to the text.


  1. <html>  
  2.   
  3. <head>  
  4.     <title>Dynamic Content</title>  
  5.     <script language="JavaScript">  
  6.         function changeMe() {  
  7.             MyHeading.outerHTML = "<H1 ID=MyHeading>Dynamic HTML!</H1>";  
  8.             MyHeading.style.color = "green";  
  9.             MyText.innerText = "You can do the most amazing things with the least bit of effort.";  
  10.             MyText.align = "center";  
  11.             document.body.insertAdjacentHTML("BeforeEnd""<P ALIGN=\"center\">Just give it a try!</P>");  
  12.         }  
  13.     </script>  
  14. </head>  
  15.   
  16. <body onclick="changeMe()">  
  17.     <h3 id="MyHeading">Welcome to Dynamic HTML!</h3>  
  18.     <p id="MyText">Click anywhere on this page.</p>  
  19. </body>  
  20.   
  21. </html>  

The sample snippet given above will change the color of the text to green, change the font size of the text, change the heading and insert new line of code when the page is clicked anywhere.

The techniques given above will put more burden on front-end coding side and are not very modular and cohesive in nature. As dynamic HTML domain matures, a new technique of front-end template is being introduced and many JavaScript based libraries like mustache, handlebars and many more are introduced.

Today, I shall be discussing about some basic features of handlebars JavaScript based front-end dynamic HTML template libraries.

Handlebars JavaScript is a client side template engine that separates HTML from JavaScript in order to create dynamic HTML. The code is easily managed, the learning curve is easy, and data interpolation is easy;  i.e., data values coming from the Server side can easily insert into the template instead of the traditional approach given below by using the string i.e. val =“some text” + data. Handlebars template engine comes with some built-in helpers and allows the developer to add custom helpers as well. It also allows us to use the template within a complex template.

Handlebars Template Engine Functional Flow 

The functional flow of handlebars template engine is given below.

  1. Handlebars template is converted into function by handlebars compiler.
  2. The data will be passed to the converted function.
  3. The converted function will return HTML, which is required.
  4. The Browser then renders HTML.

Options to Include Handlebars JavaScript

  1. Inline inclusion inside HTML page with “<script id="template-id" type="text/x-handlebars-template">Define template</script>”.

  2. Create external template, using “.handlebars” extension.

Handlebars syntax

  1. {{}} -> Any variable inside these will be rendered as a string data.
  2. {{{}}} -> This will render HTML tags define inside a string data.
  3. {{!—variable--}} -> Use for the comments.
  4. {{#}} – {{/}} -> Use for block expression e.g. if statement.
  5. ../ -> Reference parent variable within JSON data.
  6. if, each, unless & within -> Built-in helpers.

Custom Helpers

  1. Function Helpers -> Implements simple logic to get HTML.
  2. Block Helpers -> Implements complex logic to get HTML.

Handlebars Template Engine Execution Flow 

The execution flow of handlebars template engine is described, as shown below.

  1. Define the template that is packed with handlebars JavaScript syntax.
  2. Compile the template with handlebars JavaScript compile method.
  3. Provide the data context i.e. data from server side in a form of JSON to map to template.
  4. Insert or append the final HTML into your designated DOM location of HTML page.

Examples

You can follow step by step examples below or download below examples. All examples are created in plain notepad editor.

Basic "Hello World"

  1. Open Notepad editor, create an HTML page and name it "basic-1.html".
  2. Open the page in Notepad editor and paste the code given below in it i.e.
    1. <html>  
    2.   
    3. <head>  
    4.     <title> Basic-1 Demo Handlebars JavaScript </title>  
    5.     <script src="js/handlebars-v4.0.5.js"></script>  
    6.     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
    7.     <script>  
    8.         $(document).ready(function() {  
    9.             // Retrieve the template data from the HTML (jQuery is used here).  
    10.             var template = $('#basic-template1').html();  
    11.             // Compile the template data into a function  
    12.             var templateScript = Handlebars.compile(template);  
    13.             // Define data in JSON format.  
    14.             var context = {  
    15.                 "WelcomMsg""Hello World!",  
    16.                 "name""Handlebars Template Engine"  
    17.             };  
    18.             // Pass Data to template script.  
    19.             var html = templateScript(context);  
    20.             // Insert the HTML code into the page  
    21.             $(document.body).append(html);  
    22.         });  
    23.     </script>  
    24. </head>  
    25.   
    26. <body> </body>  
    27. <script id="basic-template1" type="text/x-handlebars-template">  
    28.     <div> {{WelcomMsg}} I am a {{name}}. </div>  
    29. </script>  
    30.   
    31. </html>  

In the code given above, I have created a simple handlebars JavaScript template, which will display a customized message with the customized name. Thus, let’s see the code given above step by step i.e.

  1. <script id="basic-template1" type="text/x-handlebars-template">  
  2.     <div> {{WelcomMsg}} I am a {{name}}. </div>  
  3. </script>   

The piece of code given above after body tag is a simple handlebars JavaScript template that follows handlebars template engine syntax.

  1. <script>  
  2.     $(document).ready(function() {  
  3.         // Retrieve the template data from the HTML (jQuery is used here).  
  4.         var template = $('#basic-template1').html();  
  5.         // Compile the template data into a function  
  6.         var templateScript = Handlebars.compile(template);  
  7.         // Define data in JSON format.  
  8.         var context = {  
  9.             "WelcomMsg""Hello World!",  
  10.             "name""Handlebars Template Engine"  
  11.         };  
  12.         // Pass Data to template script.  
  13.         var html = templateScript(context);  
  14.         // Insert the HTML code into the page  
  15.         $(document.body).append(html);  
  16.     });  
  17. </script>   
The piece of code given above is written inside head tag. You can also create external JavaScript for it as well and then reference it in your HTML page. In the piece of code given above, I retrieve my template first by the template ID that I have allocated for it, then compile my template to convert it into a function. I then define my sample JSON data context, then I pass my data context to my template and finally I insert my template into the body tag.

Observe here that in the code given above, my JSON data key are data context variables that I will ultimately reference into my template.

Save & Open the "basic-1.html" file in the Browser. You will see the output given below i.e.


Function Helper
  1. Open Notepad editor, create an HTML page and name it "function_helper.html".
  2. Open the page in Notepad editor and paste the code given below in it i.e.
    1. <html>  
    2.   
    3. <head>  
    4.     <title> Function Helper Demo Handlebars JavaScript </title>  
    5.     <script src="js/handlebars-v4.0.5.js"></script>  
    6.     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
    7.     <script>  
    8.         $(document).ready(function() {  
    9.             // Register helper before compiling the template.  
    10.             // "result" is name of the helper function.  
    11.             Handlebars.registerHelper("result"function(marks) {  
    12.                 if (marks >= 50) {  
    13.                     return "<span style='color: green'>passed</span>";  
    14.                 } else {  
    15.                     return "<span style='color: red'>failed</span>";  
    16.                 }  
    17.             })  
    18.             // Retrieve the template data from the HTML (jQuery is used here).  
    19.             var template = $('#basic-template1').html();  
    20.             // Compile the template data into a function  
    21.             var templateScript = Handlebars.compile(template);  
    22.             // Define data in JSON format.  
    23.             var context = {  
    24.                 "department""Computer Science",  
    25.                 "course": {  
    26.                     "name""Web Programming"  
    27.                 },  
    28.                 "students": [{  
    29.                     "fullname""Asma Khalid",  
    30.                     "marks""50"  
    31.                 }, {  
    32.                     "fullname""Muhammad Bilal Amjad",  
    33.                     "marks""80"  
    34.                 }, {  
    35.                     "fullname""John",  
    36.                     "marks""30"  
    37.                 }]  
    38.             };  
    39.             // Pass Data to template script.  
    40.             var html = templateScript(context);  
    41.             // Insert the HTML code into the page  
    42.             $(document.body).append(html);  
    43.         });  
    44.     </script>  
    45. </head>  
    46.   
    47. <body> </body>  
    48. <script id="basic-template1" type="text/x-handlebars-template">  
    49.     <div>  
    50.         <h3>This is {{course.name}} course.</h3> {{#each students}} <span style="color: blue"> <b>{{fullname}}</b></span> has {{{result marks}}} the {{../course.name}} course of {{../department}} department.<br/><br/> {{/each}} </div>  
    51. </script>  
    52.   
    53. </html>  

In the code given above, we have defined our template after body tag and processed our template inside head tag.

  1. <script id="basic-template1" type="text/x-handlebars-template">  
  2.     <div>  
  3.         <h3>This is {{course.name}} course.</h3>   
  4.         {  
  5.           {  
  6.             #each students  
  7.           }  
  8.         }   
  9. <span style="color: blue"> <b>{{fullname}}  
  10.   </b>  
  11.     </span> has {{{result marks}}} the {{../course.name}} course of {{../department}} department.<br/><br/> {{/each}}   
  12. </div>   
  13. t;/script>   

In this new template, we are using built-in function i.e. #each to loop though our list of JSON data, as defined in the data context.

  1. // Register helper before compiling the template.  
  2. // "result" is name of the helper function.  
  3. Handlebars.registerHelper("result"function(marks) {  
  4.     if (marks >= 50) {  
  5.         return "<span style='color: green'>passed</span>";  
  6.     } else {  
  7.         return "<span style='color: red'>failed</span>";  
  8.     }  
  9. })   

The piece of code given above defines our custom helper function, which will return a string base on the marks. In our provided template the "{{{result marks}}}" line will call our custom defined helper and pass the mark data from our provided JSON into it.

Save & Open the "function_helper.html" file in the browser. You will see following output i.e.


Block Paths
  1. Open Notepad Editor, create an HTML page and name it "block_paths.html".
  2. Open the page in Notepad Editor and paste the code given below in it i.e.
    1. <html>  
    2.   
    3. <head>  
    4.     <title> Block & Path Demo Handlebars JavaScript </title>  
    5.     <script src="js/handlebars-v4.0.5.js"></script>  
    6.     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
    7.     <script>  
    8.         $(document).ready(function() {  
    9.             // Retrieve the template data from the HTML (jQuery is used here).  
    10.             var template = $('#basic-template1').html();  
    11.             // Compile the template data into a function  
    12.             var templateScript = Handlebars.compile(template);  
    13.             // Define data in JSON format.  
    14.             var context = {  
    15.                 "department""Computer Science",  
    16.                 "course": {  
    17.                     "name""Web Programming"  
    18.                 },  
    19.                 "students": [{  
    20.                     "fullname""Asma Khalid"  
    21.                 }, {  
    22.                     "fullname""Muhammad Bilal Amjad"  
    23.                 }]  
    24.             };  
    25.             // Pass Data to template script.  
    26.             var html = templateScript(context);  
    27.             // Insert the HTML code into the page  
    28.             $(document.body).append(html);  
    29.         });  
    30.     </script>  
    31. </head>  
    32.   
    33. <body> </body>  
    34. <script id="basic-template1" type="text/x-handlebars-template">  
    35.     <div>  
    36.         <h3>This is {{course.name}} course.</h3> {{#each students}} My name is <span style="color: blue"> <b>{{fullname}}</b></span>. I enroll in {{../course.name}} course and my department is {{../department}}.<br/><br/> {{/each}} </div>  
    37. </script>  
    38.   
    39. </html>  
    In the piece of code given above, what we have altered in our template is that inside the #each loop is trying to access the data that is not in current context of #each loop . "{{../course.name}}" line of code moves back by using "../" and access the data which is out of context of the current #each loop.

  3. Save & Open the "block_paths.html" file in the Browser. You will see the output given below i.e.

     

Block Helper

  1. Open Notepad editor, create an HTML page and name it "block_helper.html".
  2. Open the page in Notepad editor and paste the code given below in it i.e.
    1. <html>  
    2.   
    3. <head>  
    4.     <title> Block Helper Demo Handlebars JavaScript </title>  
    5.     <script src="js/handlebars-v4.0.5.js"></script>  
    6.     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
    7.     <script>  
    8.         $(document).ready(function() {  
    9.             // Register helper before compiling the template.  
    10.             // "result" is name of the helper function.  
    11.             Handlebars.registerHelper("result"function(data, options) {  
    12.                 var len = data.length;  
    13.                 var returnData = "";  
    14.                 for (var i = 0; i < len; i++) {  
    15.                     // change the value of the passingYear to  
    16.                     // passed/not passed based on the conditions.  
    17.                     data[i].status = (data[i].marks >= 50) ? "<span style='color: green'>passed</span>" : "<span style='color: red'>failed</span>";  
    18.                     // here options.fn(data[i]) temporarily changes the  
    19.                     // scope of the whole studyStatus helper  
    20.                     // block to data[i]. So {{name}}=data[i].name  
    21.                     // in the template.  
    22.                     returnDatareturnData = returnData + options.fn(data[i]);  
    23.                 }  
    24.                 return returnData;  
    25.             });  
    26.             // Retrieve the template data from the HTML (jQuery is used here).  
    27.             var template = $('#basic-template1').html();  
    28.             // Compile the template data into a function  
    29.             var templateScript = Handlebars.compile(template);  
    30.             // Define data in JSON format.  
    31.             var context = {  
    32.                 "department""Computer Science",  
    33.                 "course": {  
    34.                     "name""Web Programming"  
    35.                 },  
    36.                 "students": [{  
    37.                     "fullname""Asma Khalid",  
    38.                     "marks""50"  
    39.                 }, {  
    40.                     "fullname""Muhammad Bilal Amjad",  
    41.                     "marks""80"  
    42.                 }, {  
    43.                     "fullname""John",  
    44.                     "marks""30"  
    45.                 }]  
    46.             };  
    47.             // Pass Data to template script.  
    48.             var html = templateScript(context);  
    49.             // Insert the HTML code into the page  
    50.             $(document.body).append(html);  
    51.         });  
    52.     </script>  
    53. </head>  
    54.   
    55. <body> </body>  
    56. <script id="basic-template1" type="text/x-handlebars-template">  
    57.     <div>  
    58.         <h3>This is {{course.name}} course.</h3> {{#result students}} <span style="color: blue"> <b>{{fullname}}</b></span> has {{{status}}} the {{../course.name}} course of {{../department}} department.<br/><br/> {{/result}} </div>  
    59. </script>  
    60.   
    61. </html>  
    The piece of code given above uses advanced techniques of the template engine i.e. block helper. What we did in it is change our context at the run time in our template, instead of using #each the built in helper, we use our own custom defined helper i.e. #result 
    1. {  
    2.     {#  
    3.         result students  
    4.     }  
    5. } < span style = "color: blue" > < b > {  
    6.     {  
    7.         fullname  
    8.     }  
    9. } < /b></span > has {  
    10.     {  
    11.         {  
    12.             status  
    13.         }  
    14.     }  
    15. }  
    16. the {  
    17.     {.. / course.name  
    18.     }  
    19. }  
    20. course of {  
    21.     {.. / department  
    22.     }  
    23. }  
    24. department. < br / > < br / > {  
    25.         {  
    26.             /result}}  
    27.             // Register helper before compiling the template.  
    28.             // "result" is name of the helper function.  
    29.             Handlebars.registerHelper("result"function(data, options) {  
    30.                 var len = data.length;  
    31.                 var returnData = "";  
    32.                 for (var i = 0; i < len; i++) {  
    33.                     // change the value of the passingYear to  
    34.                     // passed/not passed based on the conditions.  
    35.                     data[i].status = (data[i].marks >= 50) ? "<span style='color: green'>passed</span>" : "<span style='color: red'>failed</span>";  
    36.                     // here options.fn(data[i]) temporarily changes the  
    37.                     // scope of the whole studyStatus helper  
    38.                     // block to data[i]. So {{name}}=data[i].name  
    39.                     // in the template.  
    40.                     returnDatareturnData = returnData + options.fn(data[i]);  
    41.                 }  
    42.                 return returnData;  
    43.             });  
  3. Save & open the "block_helper.html" file in the Browser. You will see the output given below i.e.

     

Partial Template

  1. Open Notepad Editor, create an HTML page and name it "partial_template.html".
  2. Open the page in Notepad Editor and paste the code given below in it i.e.
    1. <html>  
    2.   
    3. <head>  
    4.     <title> Partial Template Demo Handlebars JavaScript </title>  
    5.     <script src="js/handlebars-v4.0.5.js"></script>  
    6.     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
    7.     <script>  
    8.         $(document).ready(function() {  
    9.             // Register partial template before compiling the template.  
    10.             // "templateName" is name of the helper function.  
    11.             Handlebars.registerPartial('partial''I enroll in {{courseName}} course and my department is {{department}}.');  
    12.             // Retrieve the template data from the HTML (jQuery is used here).  
    13.             var template = $('#basic-template1').html();  
    14.             // Compile the template data into a function  
    15.             var templateScript = Handlebars.compile(template);  
    16.             // Define data in JSON format.  
    17.             var context = {  
    18.                 "students": [{  
    19.                     "fullname""Asma Khalid",  
    20.                     "department""Computer Science"  
    21.                 }, {  
    22.                     "fullname""Muhammad Bilal Amjad",  
    23.                     "department""Computer Science"  
    24.                 }, {  
    25.                     "fullname""John",  
    26.                     "department""Computer Science"  
    27.                 }]  
    28.             };  
    29.             // Pass Data to template script.  
    30.             var html = templateScript(context);  
    31.             // Insert the HTML code into the page  
    32.             $(document.body).append(html);  
    33.         });  
    34.     </script>  
    35. </head>  
    36.   
    37. <body> </body>  
    38. <script id="basic-template1" type="text/x-handlebars-template">  
    39.     <div> {{#each students}} My name is <span style="color: blue"> <b>{{fullname }}</b></span>. {{> partial courseName = "Game Development" department = "IT"}} <br/><br/> {{/each}} </div>  
    40. </script>  
    41.   
    42. </html>  
    In the piece of code given above, we have defined our partial template and passed the values to our partial template on the run time , while accessing our partial template from within our template as "{{> partial courseName = "Game Development" department = "IT"}}".

  3. Save & Open the "partial_template" file in the Browser. You will see the output given below i.e.

Conclusion

In this post, you learned about handlebars template engine and dynamic HTML basic. You also learned about functional flow, syntax and execution flow of handlebars template engine. You also learned the basic of handlebars template engine through some of the basic handlebars template engine examples. You also learned about basics of dynamic HTML.

Up Next
    Ebook Download
    View all
    Learn
    View all