Blocks & Contexts in Handlebars

A block in handlebars.js is same as any other language – it’s a section of code that is grouped and placed together.
To start a block we have to prepend a “#“. => {{#Block}}
To end a block we have to prepend a “/“. => {{#Block}}

There are some pre-defined Block Helpers available in Handlebars. For example, let’s say we are traversing an array and displaying its data in Handlebars.js. We will use each Block Helper that is a block opened by {{#each varName}} and closed by {{/each}}.
[* We will understand about Block Helpers in the next post.]

Now, we have to pass data to handlebars that will be used to display content on HTML.
We pass the data as an object to handlebars function to get the result HTML and the data being passed is known as template context.

Let’s say we have the JSON data that will be passed to handlebars template is as follows :

var data = {
    subjectData : {
        name : "Physics",
        credit : "4"
    studentData : [{
        name : 'ABC',
        contact : {
            mobile : '9999', 
            email : ''
        roll : 1,
        marks : 45,
        grade : 'D'
        name : 'DEF',
        contact : {
            mobile : '8888', 
            email : ''
        roll : 2,
        marks : 68,
        grade : 'C'
        name : 'GHI',
        contact : {
            mobile : '7777', 
            email : ''
        roll : 3,
        marks : 79,
        grade : 'B'
        name : 'JKL',
        contact : {
            mobile : '98789', 
            email : ''
        roll : 4,
        marks : 53,
        grade : 'C'
        name : 'MNO',
        contact : {
            mobile : '7868', 
            email : ''
        roll : 5,
        marks : 85,
        grade : 'B'
        name : 'PQRS',
        contact : {
            mobile : '879879', 
            email : ''
        roll : 6,
        marks : 95,
        grade : 'A'

Now, we can access different levels by using

{{this}} -> current context
Dot ( . ) -> inner context
Forward-slash ( / ) -> inner context [deprecated]
dot dot ( .. ) -> parent context

Let’s write a Handlebars template to understand this better.

<script type="text/x-handlebars-template" id="ex11">
    <table border="1">
             <th> Roll </th>
             <th> Student Name </th>
             <th> Marks </th>
             <th> Subject </th>
             <th> Credits </th>
             <th> Grade </th>
              <th> Mobile </th>
       {{#each studentData}}
             <td> {{roll}} </td>
             <td> {{name}} </td>
             <td> {{marks}} </td>
             <td> {{../subjectData/name}} </td>
             <td> {{}} </td>
             <td> {{this/grade}} </td>
             <td> {{}} </td>

Ok, so now if we compile this template using following code

/* Get Template */
html = $('#ex11').html();

/* Compile */
template = Handlebars.compile(html);}

/* Generate HTML using template */
appendText = template(data);

The resulting HTML string will look something like this.

Output of the example

The Each helper block lets us loop through the data passed in this case studentData of the data object. Now the first 3 <td> is just displaying current student’s data in the iteration.
Now, what if we wanted to access subjectData. We are currently in studentData context so get to subjectData we need to go to the parent context. For this, we can use “..“.
In the 4th <td> we are using “../subjectData/name“. So, the “..” takes us to the parent context now we are at the root of the data object, to get inside subjectData we can either use “/” or “.” [Inner contexts].
You can mark the difference in 4th and 5th table row that in 5th we have 3 dots [] because first 2 dots are for going to parent context and the next dots lets us access subjectData. and then again to access any properties of subjectData we can use “/” or “.“.

Now, the next row is using this. “this” points to the current context and as we are in each block for studentData so this is pointing to studentData context & to get any information of this we can again use “/” or “.” to get to the inner context of studentData . 

We also have variables to access the index in each block helper.
{{@index}} & {{@key}}

{{@index}} => This is used to get the current index of the context.
{{@key}}     => This is used to get the current key name of the context.

So if we change the last <td> of the above example to the following :

        {{@key}} :{{this}}<br>

Then we will get output as following :

handlebars-blocksAnd that is how context and block work together in Handlebars.
In the next blog, we will look at Block Helpers. Happy Coding. 🙂



2 thoughts on “Blocks & Contexts in Handlebars

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