How to use handlebars in grails

Posted By : Shiv Kumar | 01-Jul-2014

Sometime we have required to update or insert some data in DOM after an ajax call and we do this by manually creating html markup to show the ajax response.

It looks very much handy if we have insert very much data in DOM. But using handlebars we can get out of this problem as handler provides the option of javascript templating.

It makes the task DOM updation and insertion by using the handlebars expression which are very each to use and the handlebar templates are mostly similar to html structure.

Structure to define a handlebar template is :

<script id="template_Id" type="text/x-handlebars-template">
  content to placed in template
</script>

Suppose I have to update a ul after the ajax call whose response contains a JSON data.

var container = $("#ul_id");
var dataToUpdate = "<li><span>" + data.name + "</span>" + "<div>" + data.jobDescription"</div></li>";
container.append(dataToUpdate);

Suppose my JSON response contains an array of data :

[
  records :[
 {
    name : "Jatin",
    jobDescription : "Software Engineer"
 }
 { 
    name : "Nikhil",
    jobDescription : "Designer"
 }
]
]

We can perform the same task using the handlebars and its expression very easily.

To do this we have to simple put the "contentToUpdate" in handlebars template like this :

<script id="template_Id" type="text/x-handlebars-template">
{{#each records}}      // loop to itrate through all the records
<li>
  <span>{{name}}</span>     
  <div>{{jobDescription}}</div>
</li>
{{/each}}
</script>

Compile a template in JavaScript by using Handlebars.compile

var source   = $("#template_Id").html();   // source now have content of handlerbars template
var data = Handlebars.compile(source);     // source code is compiled using this
$("#ul_id").append(template(data));        // now the target DOm in this case "ul_id" is updated with the ajax response.

It makes the DOM nsertion task easy and less efforts are required in this.

For more info , you can refer to http://handlebarsjs.com/

 

Thanks

 

Shiv Kumar

About Author

Author Image
Shiv Kumar

Shiv is a Technical Architect. He is a bright Java developer and has worked on development of various SaaS applications using Grails, Spring and Hibernate framework.

Request for Proposal

Name is required

Comment is required

Sending message..