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.
- <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 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.
- <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 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.
- Handlebars template is converted into function by handlebars compiler.
- The data will be passed to the converted function.
- The converted function will return HTML, which is required.
- The Browser then renders HTML.
Options to Include Handlebars JavaScript
- Inline inclusion inside HTML page with “<script id="template-id" type="text/x-handlebars-template">Define template</script>”.
- Create external template, using “.handlebars” extension.
Handlebars syntax
- {{}} -> Any variable inside these will be rendered as a string data.
- {{{}}} -> This will render HTML tags define inside a string data.
- {{!—variable--}} -> Use for the comments.
- {{#}} – {{/}} -> Use for block expression e.g. if statement.
- ../ -> Reference parent variable within JSON data.
- if, each, unless & within -> Built-in helpers.
Custom Helpers
- Function Helpers -> Implements simple logic to get HTML.
- 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.
- Define the template that is packed with handlebars JavaScript syntax.
- Compile the template with handlebars JavaScript compile method.
- Provide the data context i.e. data from server side in a form of JSON to map to template.
- 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"
- Open Notepad editor, create an HTML page and name it "basic-1.html".
- Open the page in Notepad editor and paste the code given below 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() {
-
- var template = $('#basic-template1').html();
-
- var templateScript = Handlebars.compile(template);
-
- var context = {
- "WelcomMsg": "Hello World!",
- "name": "Handlebars Template Engine"
- };
-
- var html = templateScript(context);
-
- $(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 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.
- <script id="basic-template1" type="text/x-handlebars-template">
- <div> {{WelcomMsg}} I am a {{name}}. </div>
- </script>
The piece of code given above after body tag is a simple handlebars JavaScript template that follows handlebars template engine syntax.
- <script>
- $(document).ready(function() {
-
- var template = $('#basic-template1').html();
-
- var templateScript = Handlebars.compile(template);
-
- var context = {
- "WelcomMsg": "Hello World!",
- "name": "Handlebars Template Engine"
- };
-
- var html = templateScript(context);
-
- $(document.body).append(html);
- });
- </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
- Open Notepad editor, create an HTML page and name it "function_helper.html".
- Open the page in Notepad editor and paste the code given below 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() {
-
-
- Handlebars.registerHelper("result", function(marks) {
- if (marks >= 50) {
- return "<span style='color: green'>passed</span>";
- } else {
- return "<span style='color: red'>failed</span>";
- }
- })
-
- var template = $('#basic-template1').html();
-
- var templateScript = Handlebars.compile(template);
-
- 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"
- }]
- };
-
- var html = templateScript(context);
-
- $(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 code given above, we have defined our template after body tag and processed 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>
- 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.
-
-
- Handlebars.registerHelper("result", function(marks) {
- if (marks >= 50) {
- return "<span style='color: green'>passed</span>";
- } else {
- return "<span style='color: red'>failed</span>";
- }
- })
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
- Open Notepad Editor, create an HTML page and name it "block_paths.html".
- Open the page in Notepad Editor and paste the code given below 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() {
-
- var template = $('#basic-template1').html();
-
- var templateScript = Handlebars.compile(template);
-
- var context = {
- "department": "Computer Science",
- "course": {
- "name": "Web Programming"
- },
- "students": [{
- "fullname": "Asma Khalid"
- }, {
- "fullname": "Muhammad Bilal Amjad"
- }]
- };
-
- var html = templateScript(context);
-
- $(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 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
- Open Notepad editor, create an HTML page and name it "block_helper.html".
- Open the page in Notepad editor and paste the code given below 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() {
-
-
- Handlebars.registerHelper("result", function(data, options) {
- var len = data.length;
- var returnData = "";
- for (var i = 0; i < len; i++) {
-
-
- data[i].status = (data[i].marks >= 50) ? "<span style='color: green'>passed</span>" : "<span style='color: red'>failed</span>";
-
-
-
-
- returnDatareturnData = returnData + options.fn(data[i]);
- }
- return returnData;
- });
-
- var template = $('#basic-template1').html();
-
- var templateScript = Handlebars.compile(template);
-
- 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"
- }]
- };
-
- var html = templateScript(context);
-
- $(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 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
- {
- {#
- result students
- }
- } < span style = "color: blue" > < b > {
- {
- fullname
- }
- } < /b></span > has {
- {
- {
- status
- }
- }
- }
- the {
- {.. / course.name
- }
- }
- course of {
- {.. / department
- }
- }
- department. < br / > < br / > {
- {
- /result}}
-
-
- Handlebars.registerHelper("result", function(data, options) {
- var len = data.length;
- var returnData = "";
- for (var i = 0; i < len; i++) {
-
-
- data[i].status = (data[i].marks >= 50) ? "<span style='color: green'>passed</span>" : "<span style='color: red'>failed</span>";
-
-
-
-
- returnDatareturnData = returnData + options.fn(data[i]);
- }
- return returnData;
- });
- Save & open the "block_helper.html" file in the Browser. You will see the output given below i.e.
Partial Template
- Open Notepad Editor, create an HTML page and name it "partial_template.html".
- Open the page in Notepad Editor and paste the code given below 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() {
-
-
- Handlebars.registerPartial('partial', 'I enroll in {{courseName}} course and my department is {{department}}.');
-
- var template = $('#basic-template1').html();
-
- var templateScript = Handlebars.compile(template);
-
- var context = {
- "students": [{
- "fullname": "Asma Khalid",
- "department": "Computer Science"
- }, {
- "fullname": "Muhammad Bilal Amjad",
- "department": "Computer Science"
- }, {
- "fullname": "John",
- "department": "Computer Science"
- }]
- };
-
- var html = templateScript(context);
-
- $(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 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"}}".
- 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.