Request Quote

Handlebars Templating engines

In this blog we will read something about Handlebars templating engines.Whenever we need to dynamic binding of data in html or to manipulate DOM with dynamic data we prefer templating engines. Here lets have an short intro of Handlebar templating engine in our project.

    {{#each this}}
  • Name : {{ name }}

    Email : {{ email }}

    Website : {{ website }} ( {{company.name}} )

    Address : {{ postalAddress address }}

  • {{/each}}
(function(){ var Handles = { init : function () { this.url = "https://jsonplaceholder.typicode.com/users"; this.fetch(); }, fetch : function(){ $.getJSON( this.url , function( data ){ var source = $("#testing-template").html(); var temp = Handlebars.compile(source); // passing template to handlebar to compile ,returns function $('ul.vendors').append(temp(data)); // pass json data to function which contains values of the variable of template,return desired html content }); //We are registering a custom helper here which will return postal address of vendors . Handlebars.registerHelper('postalAddress', function(address) { return address.street + " " + address.city + " " + address.zipcode; }); } }; Handles.init(); })();

What we did here is we get template from its id and pass it to Handlebars , handlebar receives the template with variable and compile it to function , then we provide json data which contains value of variables used in template so that they can be replaced.
Here we are calling Handlebars.compile to compile our handlebars but it is prefarable to compile handlebars before rendering than to compile it in browser.

In above code i register a custom helper using Handlebars.registerHelper there are some in built helpers too such as

    if
    each
    unless etc

In order to precompile your handlebars here are the steps :
1. Open node cmd and run command as : npm install handlebars -g
It will install handlebar globally.
2. Create a file naming testing-template.handlebar and write your template related code in it as :

    {{#each this}}
  • Name : {{ name }}

    Email : {{ email }}

    Website : {{ website }} ( {{company.name}} )

  • {{/each}}


3. Traverse path upto your file and run command : handlebars -f test.js testing-template.handlebar . It will create a js file

4. Improve your previous html code and include this js file as :
a. Include previously created js file in your code.
b. put this code in your html body :

    (function(){ var Gdistance = { init : function () { this.url = "https://jsonplaceholder.typicode.com/users"; this.fetch(); }, fetch : function(){ $.getJSON( this.url , function( data ){ var template = Handlebars.templates['ankita-template.handlebar'], // your template minus the .js context = data, // your data html = template(context); $('ul.vendors').html(html); }); } }; Gdistance.init(); })();

    For detail you can refer : Handlebars

    . . .

    Comment

    Add Your Comment

    Be the first to comment.

    css.php