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 of dynamic HTML was to introduce re-usability of code for data bound web content e.g. when using data in lists, table etc that requires a large amount of data to be displayed but with similar styling or visual format. Not only that to induce more user interactivity e.g. displaying customize messages into customize HTML message box instead of just displaying typical alerts during system response to every user action. These requirements for the modern state of the art websites with more user friendliness and user interactivity in play requires a more versatile techniques from the front-end side.

Before I jump into what Handlebars JavaScript is all about let me share some of the example of usage of dynamic HTML i.e.

<html>  
 <head>  
 <title>Dynamic Styles</title>  
 <script language="JavaScript">  
 function doChanges(e) {  
   e.style.color = "green";  
   e.style.fontSize = "20px";  
 }  
 </script>  
 </head>  
 <body>  
 <h3 onmouseover="doChanges(this)" style="color:black;font-size:18px">Welcome to Dynamic HTML!</h3>  
 </body>  
 </html>

 

The above sample snippet will change the color of the text to green and change font size of the text when a mouse cursor will move over to the text.

<html>  
 <head><title>Dynamic Content</title>  
 <script language="JavaScript">  
 function changeMe() {  
   MyHeading.outerHTML = "<H1 ID=MyHeading>Dynamic HTML!</H1>";  
   MyHeading.style.color = "green";  
   MyText.innerText = "You can do the most amazing things with the least bit of effort.";  
   MyText.align = "center";  
   document.body.insertAdjacentHTML("BeforeEnd", "<P ALIGN=\"center\">Just give it a try!</P>");  
 }  
 </script>  
 </head>  
 <body onclick="changeMe()">  
 <h3 id="MyHeading">Welcome to Dynamic HTML!</h3>  
 <p id="MyText">Click anywhere on this page.</p>  
 </body>  
 </html>

 

The above sample snippet 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 click anywhere.

The above techniques will  put more burden on front-end coding side and is 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 base libraries like mustache, handlebars and many more are introduced.

Today, I shall be discussing about some basic feature of Handlebars JavaScript base front-end dynamic HTML template library.

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

Handlebars Template Engine Functional Flow

The functional flow of Handlebars template engine is describes as follow i.e.

1) Handlebars template is converted into function by Handlebars compiler.
2) Data will be passed to the converted function.
3) Converted function will return HTML which is required.
4) Browser then render the HTML.

Options to Include Handlebars JavaScript

1) Inline inclusion inside HTML page with “Define template”.

2) Create External Template using “.handlebars” extension.

Handlebars Syntax

1) {{}} -> Any variable inside these will be rendered as string data.
2) {{{}}} -> This will render html tags define inside a string data.
3) {{!—variable–}} -> Use for 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 -> Implement simple logic to get HTML.

2) Block Helpers -> Implement Complex logic to get HTML.

Handlebars Template Engine Execution Flow

The execution flow of Handlebars template engine is describes as follow i.e.

1) Define template that is packed with Handlebars JavaScript syntax.
2) Compile the template with Handlebars JavaScript compile method.
3) Provide 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.

Download Link

1) 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 following code in it i.e.
<html>  
      <head>  
           <title> Basic-1 Demo Handlebars JavaScript </title>  
     <script src="js/handlebars-v4.0.5.js"></script>  
     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
     <script>   
                $(document).ready(function ()  
                {            
                     // Retrieve the template data from the HTML (jQuery is used here).  
                     var template = $('#basic-template1').html();  
                     // Compile the template data into a function  
                     var templateScript = Handlebars.compile(template);  
                     // Define data in JSON format.  
                     var context = { "WelcomMsg" : "Hello World!",   
                                         "name" : "Handlebars Template Engine" };  
                     // Pass Data to template script.  
                     var html = templateScript(context);  
                     // Insert the HTML code into the page  
                     $(document.body).append(html);            
     });                 
     </script>  
   </head>  
   <body>  
   </body>  
      <script id="basic-template1" type="text/x-handlebars-template">  
     <div>  
      {{WelcomMsg}} I am a {{name}}.  
     </div>  
   </script>    
 </html>

 

In above code, I have created a simple Handlebars JavaScript template that will display a customize message with customize name. So, let’s see above code step by step i.e.

 

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

 

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

 

<script>   
                $(document).ready(function ()  
                {            
                     // Retrieve the template data from the HTML (jQuery is used here).  
                     var template = $('#basic-template1').html();  
                     // Compile the template data into a function  
                     var templateScript = Handlebars.compile(template);  
                     // Define data in JSON format.  
                     var context = { "WelcomMsg" : "Hello World!",   
                                         "name" : "Handlebars Template Engine" };  
                     // Pass Data to template script.  
                     var html = templateScript(context);  
                     // Insert the HTML code into the page  
                     $(document.body).append(html);            
     });                 
     </script>

 

The above piece of code 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 above piece of code, I retrieve my template first by the template ID that I have allocate for it, then compile my template to convert it into a functions. I then define my sample JSON data context, then I pass my data context to my template and finally I insert my template into body tag.

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

3) Save & Open the “basic-1.html” file in the browser. You will see following output i.e.

2) 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 following code in it i.e.

<html>  
      <head>  
           <title> Function Helper Demo Handlebars JavaScript </title>  
     <script src="js/handlebars-v4.0.5.js"></script>  
     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
     <script>   
                $(document).ready(function ()  
                {            
                  // Register helper before compiling the template.  
                     // "result" is name of the helper function.  
                     Handlebars.registerHelper("result", function(marks)   
                     {  
                       if(marks >= 50)   
                       {  
                           return "<span style='color: green'>passed</span>";  
                       }   
                       else   
                       {  
                           return "<span style='color: red'>failed</span>";  
                       }  
                     })                                          
                     // Retrieve the template data from the HTML (jQuery is used here).  
                     var template = $('#basic-template1').html();  
                     // Compile the template data into a function  
                     var templateScript = Handlebars.compile(template);  
                     // Define data in JSON format.  
                     var context = { "department" : "Computer Science",   
                                         "course" : { "name": "Web Programming" },  
                                         "students" : [ {"fullname":"Asma Khalid", "marks":"50"},  
                                                 {"fullname":"Muhammad Bilal Amjad", "marks":"80"},  
                                                          {"fullname":"John", "marks":"30"}] };  
                     // Pass Data to template script.  
                     var html = templateScript(context);  
                     // Insert the HTML code into the page  
                     $(document.body).append(html);                           
     });                 
     </script>  
   </head>  
   <body>  
   </body>  
      <script id="basic-template1" type="text/x-handlebars-template">  
     <div>  
                <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>  
   </script>    
 </html>

 

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

 

<script id="basic-template1" type="text/x-handlebars-template">  
     <div>  
                <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>  
   </script>

 

Notice that 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.

 

                 // Register helper before compiling the template.  
                     // "result" is name of the helper function.  
                     Handlebars.registerHelper("result", function(marks)   
                     {  
                       if(marks >= 50)   
                       {  
                           return "<span style='color: green'>passed</span>";  
                       }   
                       else   
                       {  
                           return "<span style='color: red'>failed</span>";  
                       }  
                     })  

 

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

3) Save & Open the “function_helper.html” file in the browser. You will see following output i.e.

3) 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 following code in it i.e.

<html>  
      <head>  
           <title> Block & Path Demo Handlebars JavaScript </title>  
     <script src="js/handlebars-v4.0.5.js"></script>  
     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
     <script>   
                $(document).ready(function ()  
                {            
                     // Retrieve the template data from the HTML (jQuery is used here).  
                     var template = $('#basic-template1').html();  
                     // Compile the template data into a function  
                     var templateScript = Handlebars.compile(template);  
                     // Define data in JSON format.  
                     var context = { "department" : "Computer Science",   
                                         "course" : { "name": "Web Programming" },  
                                         "students" : [ {"fullname":"Asma Khalid"},  
                                                 {"fullname":"Muhammad Bilal Amjad"}] };  
                     // Pass Data to template script.  
                     var html = templateScript(context);  
                     // Insert the HTML code into the page  
                     $(document.body).append(html);            
     });                 
     </script>  
   </head>  
   <body>  
   </body>  
      <script id="basic-template1" type="text/x-handlebars-template">  
     <div>  
                <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>  
   </script>    
 </html>

 

In the above piece of code what we have alter in our template is that we inside the #each loop is trying to access the data that is not in current context of #each loop . “{{../course.name}}”  line of code move back up by using “../” and access the data which is out of context of current #each loop.

3) Save & Open the “block_paths.html” file in the browser. You will see following output i.e.

4) 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 following code in it i.e.

<html>  
      <head>  
           <title> Block Helper Demo Handlebars JavaScript </title>  
     <script src="js/handlebars-v4.0.5.js"></script>  
     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
     <script>   
                $(document).ready(function ()  
                {            
                  // Register helper before compiling the template.  
                     // "result" is name of the helper function.  
                     Handlebars.registerHelper("result", function(data, options)  
                     {  
                           var len = data.length;  
                           var returnData="";  
                           for(var i=0;i<len;i++)  
                           {  
                               // change the value of the passingYear to  
                               // passed/not passed based on the conditions.  
                               data[i].status = (data[i].marks >= 50) ? "<span style='color: green'>passed</span>" : "<span style='color: red'>failed</span>";  
                               // here options.fn(data[i]) temporarily changes the  
                               // scope of the whole studyStatus helper  
                               // block to data[i]. So {{name}}=data[i].name  
                               // in the template.  
                               returnData = returnData + options.fn(data[i]);  
                           }  
                           return returnData;  
                     });                                
                     // Retrieve the template data from the HTML (jQuery is used here).  
                     var template = $('#basic-template1').html();  
                     // Compile the template data into a function  
                     var templateScript = Handlebars.compile(template);  
                     // Define data in JSON format.  
                     var context = { "department" : "Computer Science",   
                                         "course" : { "name": "Web Programming" },  
                                         "students" : [ {"fullname":"Asma Khalid", "marks":"50"},  
                                                 {"fullname":"Muhammad Bilal Amjad", "marks":"80"},  
                                                          {"fullname":"John", "marks":"30"}] };  
                     // Pass Data to template script.  
                     var html = templateScript(context);  
                     // Insert the HTML code into the page  
                     $(document.body).append(html);                           
     });                 
     </script>  
   </head>  
   <body>  
   </body>  
      <script id="basic-template1" type="text/x-handlebars-template">  
     <div>  
                <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>  
   </script>    
 </html>

 

The above piece of code use advance technique of template engine i.e. block helper. What we did in it is change our context at run time and also now in our template instead of using #each the built in helper we use our own custom defined helper i.e. #result i.e.

               {{#result students}}  
                     <span style="color: blue"> <b>{{fullname}}</b></span> has {{{status}}} the {{../course.name}} course of {{../department}} department.<br/><br/>  
                {{/result}}  
                 // Register helper before compiling the template.  
                     // "result" is name of the helper function.  
                     Handlebars.registerHelper("result", function(data, options)  
                     {  
                           var len = data.length;  
                           var returnData="";  
                           for(var i=0;i<len;i++)  
                           {  
                               // change the value of the passingYear to  
                               // passed/not passed based on the conditions.  
                               data[i].status = (data[i].marks >= 50) ? "<span style='color: green'>passed</span>" : "<span style='color: red'>failed</span>";  
                               // here options.fn(data[i]) temporarily changes the  
                               // scope of the whole studyStatus helper  
                               // block to data[i]. So {{name}}=data[i].name  
                               // in the template.  
                               returnData = returnData + options.fn(data[i]);  
                           }  
                           return returnData;  
                     });  

3) Save & Open the “block_helper.html” file in the browser. You will see following output i.e.

5) 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 following code in it i.e.

<html>  
      <head>  
           <title> Partial Template Demo Handlebars JavaScript </title>  
     <script src="js/handlebars-v4.0.5.js"></script>  
     <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>  
     <script>   
                $(document).ready(function ()  
                {            
                  // Register partial template before compiling the template.  
                     // "templateName" is name of the helper function.  
                     Handlebars.registerPartial('partial',  
                      'I enroll in {{courseName}} course and my department is {{department}}.'  
                     );  
                     // Retrieve the template data from the HTML (jQuery is used here).  
                     var template = $('#basic-template1').html();  
                     // Compile the template data into a function  
                     var templateScript = Handlebars.compile(template);  
                     // Define data in JSON format.  
                     var context = { "students" : [ {"fullname":"Asma Khalid", "department" : "Computer Science"},  
                                                 {"fullname":"Muhammad Bilal Amjad", "department" : "Computer Science"},  
                                                          {"fullname":"John", "department" : "Computer Science"}] };  
                     // Pass Data to template script.  
                     var html = templateScript(context);  
                     // Insert the HTML code into the page  
                     $(document.body).append(html);                           
     });                 
     </script>  
   </head>  
   <body>  
   </body>  
      <script id="basic-template1" type="text/x-handlebars-template">  
     <div>                      
                {{#each students}}  
                     My name is <span style="color: blue"> <b>{{fullname }}</b></span>. {{> partial courseName = "Game Development" department = "IT"}} <br/><br/>  
                {{/each}}  
     </div>  
   </script>    
 </html>

 

In the above piece of code we have defined our partial template and pass values to our partial template on 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 following output i.e.

 Conclusion

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

Leave a Reply