Partials & Utils in Handlebars


Let’s say we have a structure like the following :

data = {
 students : [{
   name : 'ABC',
   roll : 1
   name : 'DEF',
   roll : 2
   name : 'GHI',
   roll : 3

 subject : [{
   name : "Programming in C",
   credits : 4
   name : 'Data Structures using C',
   credits : 3
   name : 'Object Oriented Programming with C++',
   credits : 4

And you want to show the list of users as well as the list of subjects. You will have to write the each block 2 times with different context and displaying “name“. It would have been nice if we can reuse template for this.

Handlebars allows for template reuse through partials. Partials in handlebars are useful when you want to use a piece of the template in different contexts.
Expression for Partials in handlebars is : {{> partial}}.

<script type="text/x-handlebars-template" id="ex10">
        {{#each students}}
           {{> person}}
        {{#each subject}}
           {{> person}}

If you see we are using {{> person}} partial. We have to now define this partial.

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

After defining this Handlebars still does not know about this partial. We will have to register this partial to use it. To register this we will have to execute the following code.

Handlebars.registerPartial("person", $("#person-subject-partial").html());

After this if we will compile our template then partial will come into effect. And we will get the following :


Note : Partials may be precompiled and the precompiled template passed into the second parameter.


There are variety of utility methods that can be accessed using Handlebars.Utils object. Let’s look at some of the Utility functions :

> Handlebars.Utils.escapeExpression(string) : Escapes HTML from string making it safe to be rendered as text in HTML. Replaces &, <, >, “, ‘, `, = with the HTML entity equivalent value for string values.

> Handlebars.Utils.isEmpty(value) :
Checks if given value is empty. Returns true if empty otherwise returns false.

> Handlebars.Utils.toString(obj) :
Generic toString method. Converts the obj to a string.

> Handlebars.Utils.isArray(obj) :
Checks if obj is an array. Returns true if obj is an array otherwise returns false.

> Handlebars.Utils.isFunction(obj) : Checks if obj is a function. Returns true if obj is a function otherwise returns false.

And this blog marks the completion of the Handlebars series.
Try Handlebars it is really helpful and easy to use.

Big Thumbs Up To [References] :!/blog/2012/handlebarsjs/

Happy Coding. 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s