HTML5 Zone is brought to you in partnership with:

Seasoned technology professional with strong experience in developing desktop applications, web applications, mobile web applications, web services platform based on multi-tiered distributed architecture, legacy modernization, and SOA. Senthamizh Chelvi has posted 8 posts at DZone. You can read more from them at their website. View Full User Profile

Handlebars.js in a Nutshell

04.26.2013
| 4417 views |
  • submit to reddit

Handlebars Overview

Handlebars.js is a logic-less semantic web template framework.  The 3 main parts of Handlebars are Handlebars template, data/context in JSON format and Handlebars compile function.

How Handlebars Works?

Handlebars Syntax/Features

  • Expressions - are the basic unit of Handlebars template representing property in the data/context.  
  • Built-In Block Helpers - are the conditionals and loops for executing logic
  • Custom Helpers - are user defined JavaScript functions to manipulate/process the data  and implement any kind of complex logic.
  • Path -  A path is a property lookup. Nested paths to lookup property of the current data/context and Parent path ../ to lookup property on parent of the current data/context.
  • Partials (sub templates) - To render a section of a template marked with "partial name" within a larger template, with another template.
  • Pre-compilation – Saves time on the client and reduces run-time size of the Handlebars.js library

When to use a Handlebars.js Templating Engine?

  • Application’s view will be updated frequently, especially as a result of changes to the data either from the server or the client
  • Multiple technology stacks that depend on the same data (server)
  • When the application has much interactivity and it is very responsive
  • To develop a single-page web application with multiple views
  • To easily manage HTML content; you don’t want your JavaScript code to contain important HTML markup

How to Load/Add Templates

1. In-lined Templates using <script> tag

<script id="template" type="text/x-handlebars-template">
</script>


2. Externalized Templates

Storing templates in files and retrieve them using Require.js
Storing templates in DB and  retrieve them using RESTful interface through Ajax calls

References

Published at DZone with permission of its author, Senthamizh Chelvi Kaliyaperumal.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)