Dynamic HTML Using Handlebars JavaScript (by Asma Khalid)

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.     “JavaScript”>  
  6.         function doChanges(e) {  
  7.             e.style.color = “green”;  
  8.             e.style.fontSize = “20px”;  
  9.         }  
  10.       
  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.     “JavaScript”>  
  6.         function changeMe() {  
  7.             MyHeading.outerHTML = 

    Dynamic HTML!

    ;  
  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”

    Just give it a try!

    );  
  12.         }  
  13.       
  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 “Define template”.

  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.     “js/handlebars-v4.0.5.js”>  
    6.     “http://code.jquery.com/jquery-latest.min.js” type=“text/javascript”>  
    7.       
    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.       
    24. </head>  
    25.   
    26. <body> </body>  
    27. “basic-template1” type=“text/x-handlebars-template”>  
    28.    
       {{WelcomMsg}} I am a {{name}}. 

        

    29.   
    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. “basic-template1” type=“text/x-handlebars-template”>  
  2.    
     {{WelcomMsg}} I am a {{name}}. 

      

  3.   

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

  1.   
  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.   

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.     “js/handlebars-v4.0.5.js”>  
    6.     “http://code.jquery.com/jquery-latest.min.js” type=“text/javascript”>  
    7.       
    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 passed;  
    14.                 } else {  
    15.                     return failed;  
    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.       
    45. </head>  
    46.   
    47. <body> </body>  
    48. “basic-template1” type=“text/x-handlebars-template”>  
    49.    
        
    50.        

      This is {{course.name}} course.

       {{#each students}} “color: blue”{{fullname}} has {{{result marks}}} the {{../course.name}} course of {{../department}} department.

       {{/each}} 

  

  •   
  •   
  • </html>  
  • In the code given above, we have defined our template after body tag and processed our template inside head tag.

    1. “basic-template1” type=“text/x-handlebars-template”>  
    2.    
        
    3.        

      This is {{course.name}} course.

         

    4.         {  
    5.           {  
    6.             #each students  
    7.           }  
    8.         }   
    9. “color: blue”{{fullname}}  
    10.     
    11.      has {{{result marks}}} the {{../course.name}} course of {{../department}} department.

       {{/each}}   

       

  • 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 passed;  
    6.     } else {  
    7.         return failed;  
    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.   
      2.   
      3.   
      4.      Block & Path Demo Handlebars JavaScript   
      5.     “js/handlebars-v4.0.5.js”>  
      6.     “http://code.jquery.com/jquery-latest.min.js” type=“text/javascript”>  
      7.       
      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.       
      31. </head>  
      32.   
      33. <body> </body>  
      34. “basic-template1” type=“text/x-handlebars-template”>  
      35.    
          
      36.        

        This is {{course.name}} course.

         {{#each students}} My name is “color: blue”{{fullname}}. I enroll in {{../course.name}} course and my department is {{../department}}.

         {{/each}} 

      

  •   
  •   
  • </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.

  • 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.     “js/handlebars-v4.0.5.js”>  
      6.     “http://code.jquery.com/jquery-latest.min.js” type=“text/javascript”>  
      7.       
      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 
      15.                     // change the value of the passingYear to  
      16.                     // passed/not passed based on the conditions.  
      17.                     data[i].status = (data[i].marks >= 50) ? passed : failed;  
      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.       
      53. </head>  
      54.   
      55. <body> </body>  
      56. “basic-template1” type=“text/x-handlebars-template”>  
      57.    
          
      58.        

        This is {{course.name}} course.

         {{#result students}} “color: blue”{{fullname}} has {{{status}}} the {{../course.name}} course of {{../department}} department.

         {{/result}} 

      

  •   
  •   
  • </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.             });  
  • 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.     “js/handlebars-v4.0.5.js”>  
      6.     “http://code.jquery.com/jquery-latest.min.js” type=“text/javascript”>  
      7.       
      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.       
      35. </head>  
      36.   
      37. <body> </body>  
      38. “basic-template1” type=“text/x-handlebars-template”>  
      39.    
         {{#each students}} My name is “color: blue”{{fullname }}. {{> partial courseName = “Game Development” department = “IT”}} 

         {{/each}} 

          

      40.   
      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.

    Bir Cevap Yazın

    E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

    TOP