Dynamic HTML Using Handlebars JavaScript
<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
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
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 Now!
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.
In the above code we have defined our template after body tag and process our template inside head tag.
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.
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.
2) Open the page in notepad editor and paste the following code in it i.e.
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.
2) Open the page in notepad editor and paste the following code in it i.e.
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.
3) Save & Open the "block_helper.html" file in the browser. You will see following output i.e.
2) Open the page in notepad editor and paste the following code in it i.e.
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.
<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.
This is one of the most useful things I have read in a long time. Thanks! aerospace website development
ReplyDeleteGreat Article
ReplyDeleteCyber Security Projects for CSE Students
JavaScript Training in Chennai
Project Centers in Chennai
JavaScript Training in Chennai
I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. SEO expert Singapore at www.dynamicmarketing.sg/seo-consultant-singapore
ReplyDeleteSome truly wonderful work on behalf of the owner of this internet site , perfectly great articles . https://www.dynamicmarketing.sg/seo-consultant-singapore
ReplyDeleteThank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. ig likes uk
ReplyDeleteThere is noticeably a bundle to know about this. I assume you have made certain nice points in functions also. web design la
ReplyDeleteHello There. I found your blog using msn. This is a really well written article. I’ll be sure to bookmark it and return to read more of your useful information. Thanks for the post. I’ll certainly comeback. web design company los angeles
ReplyDeleteThank you for your support and appreciation.
ReplyDelete