Sunday, February 25, 2018

Best Handlebars tutorial with demo

What will you get from this article?

When you will finish to read this article, you'll know client-side templating and how to do this with Handlebars.js, and how it worths to give a try.
You will explore main features of Handlebars.js for better templating, like, built-in helpers/custom-helpers to add the logic in your template, partial for modularizing the code, and precompile the templates to increase the dom rendering speed and automation of precompiling process with Grunt.


What’s client-side templating?

Before dive into the Handlbars.js, we need to understand what is client-side templating first. Every experience web developer might have some experience of writing JavaScript to generate HTML, something like,
    var person = {name:suman, age : 30} 
    var elem = document.createElement('div');
    elem.innerHTML =  'name=' + person.name + ' age=' + person.age
    result.appendchild(elem );
    
Now, think of above code as thousands line on the large and complex project, it would be error prone, sluggish, and hard to maintain. We need to separate those UI JavaScript codes with the tool which is easy to use, maintain, and flexible.

After using templates on the projects, a person works on it does not need deep programming to make UI better, because template file is similar to HTML which is easy to modify via changing the tags, attributes and the position of tags.

For example, above code can be written in Handlebars something like
name = {{ name }} age = {{age }}
So client-side templating is the tool to use the generate HTML using provided data with its own syntax. All we do this to separate the data and presentation code.

After using templates on the projects, a person works on it does not need deep programming to make UI better, because template file is similar to HTML which is easy to modify via changing the tags, attributes and the position of tags.

What is handlebars.js?

hanldebars tutorial

Handlebars is an open source JavaScript template engine which is inherited from Mustache.js, is used to separate the UI code from the business code. It's semantic template
language, which means, the HTML is created as a string, would be inserted in your web page.

For example, the template code <h3>{{site}}</h3> would be converted to <h3>smashingmagazine.com</h3>, and ready to use at the web page. It's famous for client-side templating but this can be used on server templating as well, in this article we will focus on the client.
The Handlebars syntax is quite similar to syntax of other templates-engine, like,

Mustache.js
var context = {site : smashmagzin.com };

{{site}}


Dust.js
var context = {site : smashmagzin.com };

{site}


Handlebars.js
var context = {site : smashmagzin.com };

{{site}}


In Handlebars.js, the {{site}} expression fetches the data from context while compiling and outputs as  <h3>smashmagzin.com</h3>.

Why should we use handlebars.js?



Handlebars is very easy to use and flexible, it's built on top of Mustache, it supports all Mustache syntax which is known for logicless templating while using Handlebars helper, you can add the logic to your template for flexibility. You can use the built-in helper like if, unless, each(loop helper) and can create the custom helper.
You can precompile the templates into single JS file to increase the faster dom rendering. As compared to Mustache templates, it's 5 to 7 time faster by using precompiling. The feature like partial can be used to modularize your HTML/UI code. The Handlebars is using within top tools like Ember.js and hbs(template engine) of Express.js. It's fast-growing and widely community supported template engine. As of writing, 141 contributors, 1675 forks and 12994 stars on Github prove that. The Handlebars supports in all major browsers, like, Chrome Firefox, Safari and Internet Explorer.

How to use handlebars with the simple demo?

To use the Handlebars, you need to add a single file handlebars.min.js in your web page and start writing your template, below is the simple demo,

See the Pen handlebars-simple-demo by suman bogati (@sumanbogati) on CodePen.


We define the templates in a script tag and its type is “text/-x-handlebars-template”, by doing so the template content does not display into a browser.

Compiling the templates by Handlebars.compile(elem) returns the function which accepts the data-context as the parameters, now it can be invoked by passing the actual data, and finally, this function returns the string of HTML.

Important features

The template is a successor of Mustache, It supports all the features that Mustache has, and it's additional features make it very flexible and robust tool.

Expression converts ideas in reality
The name/property exists between the curly braces is the expression. Using the expression in Handlebars template, you can get the data from context object, we already have seen the use of an expression in above points.

Data
var context = {lang: english, country: England} 
View presentation
Speaking is = {{lang}}  of {{country}}
lang and country are expressions which are overridden by the data/values english and england after compiling the template.

The value returned by an expression {{propname}} is html-escaped, which means, if you write  {{<h2>hello world </h2>}}, then it outputs <h2>hello world </h2> as result, handlebars does not execute html to prevent XSS attack. 

But there might be the case where you need to execute the HTML code, where you can use triple curly braces {{{...}}} enclosing a variable, like  {{{<h3>Smashing magazine</h3> }}}, which outputs the header Smashing magazine. 

Now you might have a question that what about XSS attack? Handlebars.SafeString() rescues you from this situation, you need to do just new Handlebars.SafeString( {{{<h3>Smashing magazine</h3> }}}) and you are secure.

There is two type of expression: one, the header example at above is single expression;  other is block expression which has two pairs of curly braces opening and closing, like
{{#if homePage}}
   
{{productList}}
{{/if}}
As you can see, the if has the opening and closing tag. In this block expression, homePage looks up 'true' value in current context.

Helpers respone your query

Helpers are used to adding logic in your template, there is two kinds of helper one is built-in other is custom helper which can be created by the user.


Built-in helpers are: {{ #if...}} {{/if}}, {{ #unless...}} {{/unless}} and {{ #each ...} {{/each}}
'
{{#if ...}} helper is used to add the logic of if condition in your template, for example, you want to display the “thank you” message if form is submitted already, like
{{#if formSubmit}}
    

Thank you {{user}}, for submit the form,

{{/if}}
Above block will be executed if formSubmit is true.

In case of form not submitted, you can use the else condition to display the form, when all come together it looks like,
{{#if formSubmit}}
    

Thank you {{user}}, for submit the form,

{{/if}} {{#if formSubmit}}

Thank you {{user}}, for submit the form,

{{else}}
form content here.. .
{{/if}}
{{#unless ...}} is opposite of {{#if ...}}, the condition is true when a variable with “unless” returns the falsy value like, the below block will be rendered when “formSubmit” is false,
{{#unless formSubmit}}
    
form content here..
{{/unless}}

{{#each ...}} helper is used to repeat your template with provided data, for example in below demo,
the loop helper is used to iterates the item of array(people)

See the Pen Handlebars-each-helper by suman bogati (@sumanbogati) on CodePen.

Custom Helper

You can create your own helper with handlebars, suppose, in a template, you need the function
that will fetch the relative string from language object using the provided key.
var langEn = {
  success : 'The file has been uploaded successfully'
}

var getString = function (key){
   return   langEn[key]
}
Handlebars.registerHelper('getString');

{{#getString success}}

The result for {{#getString success}} would be “The file has been uploaded successfully”.
Partial simplifies your life

Partial is used to modularize the template code which eventually will be rendered as html, its handy when we work on large and complex project. You can reduce the template code using the partial, for example, header and footer are similar to all web pages of a website, so you can create this in partial and use it wherever you want. The below example is shown with two different template files,
Header Template (header.hbs)

Main Template (main.hbs)
{{ >> header }}
JavaScript
Handlebars.registerPartial('header ', Handlebars.getTemplates('header'));
As you can see in above example, you can use the header partial at the place you want by locating {{ >> header }}, now you might have imagined already how much its helpful to make template code modularize, easy to use, and maintainable. You can register the partial with Handlebars.registerPartial() function and can be invoked it by using {{ >> partialName}} like we have done with the header in above example.
Precompiling saves your resources
Many templates-compilation on the fly could be the performance bottleneck and cause as slow rendering in the browser. So you can precompile all template code into single JS file on your machine first, which drastically improves the rendering performance. This feature takes Handlebars ahead than other template engines.
How to precocmpiling the template?
For precompiling the template you need to install following tools on your machine:
  1. You can find how to Install nodejs on your system.
  2. After installing nodejs, next, install Handlebars.js npm package by
  3. npm install handlebars -g
  4. Now you can precompile the templates by executing the following command from your project directory
  5. handlebars <input> -f <output>
In above command, an input is template file and output is the template-converted-js file, that JS file can be added to your webpage and can be rendered as HTML without compiling on the fly.
You can save the time and effort by automating all this process, so, what's needs to be done for this?

We already have Node.js and Handlebars.js npm package
  1. Next, install grunt in your project directory by
  2. sudo npm install grunt --save-dev
  3.  Next, install the grunt-handlebars.js plugin which precompile the templates  (.hbs to .js), 
  4. npm install grunt-contrib-handlebars --save-dev 
Here .hbs is your template files which will be converted at JavaScript functions in a JS file.
Next, you can configure Gruntfile.js in your project directory, like the location of your templates file and location of converted JS file.
handlebars: {
    // converting all .hbs(handlebars templates file ) into all.js file
    all: { files: { "js/all.js": ["templates/*.hbs"]}} 
}
Here is the sample Gruntfile.js which you can use in your project directory, don't forget to edit according
to your requirements. After setting up this, go to project directory by cd in terminal/command-prompt, now you can type the grunt to pre-compile the templates to all.js file.
Conclusion
In modern days of web development, it becomes essential that creating new features, fixing bugs and enhancement of existing feature should be performed on high speed, for that your code need be organized, readable and easy to maintain.
Using template engine you can ensure that your UI code is separate from business code, Handlebars helps you to modularize the code, fast dom rendering and add extreme flexibility to your template with great features.
What's next?
You can find more about Handlebars.
TryHandlebars gives the opportunity to practice online.
Want to participate as a contributor, find the Handlebars at Github.

No comments:

Post a Comment