Blocks & Contexts in Handlebars
by Prabhat Rai

Posted on January 12, 2015 at 04:44 PM


Featured Image

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 : 'cyz@xyz.com'
},
roll : 1,
marks : 45,
grade : 'D'
},{
name : 'DEF',
contact : {
mobile : '8888',
email : 'dzfs@xyz.com'
},
roll : 2,
marks : 68,
grade : 'C'
},{
name : 'GHI',
contact : {
mobile : '7777',
email : 'asfasf@xyz.com'
},
roll : 3,
marks : 79,
grade : 'B'
},{
name : 'JKL',
contact : {
mobile : '98789',
email : 'asfas@xyz.com'
},
roll : 4,
marks : 53,
grade : 'C'
},{
name : 'MNO',
contact : {
mobile : '7868',
email : 'asfas@xyz.com'
},
roll : 5,
marks : 85,
grade : 'B'
},{
name : 'PQRS',
contact : {
mobile : '879879',
email : 'asfafs@xyz.com'
},
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">
       <thead>
          <tr>
             <th> Roll </th>
             <th> Student Name </th>
             <th> Marks </th>
             <th> Subject </th>
             <th> Credits </th>
             <th> Grade </th>
              <th> Mobile </th>
       </tr>
       {{#each studentData}}
          <tr>
             <td> {{roll}} </td>
             <td> {{name}} </td>
             <td> {{marks}} </td>
             <td> {{../subjectData/name}} </td>
             <td> {{...subjectData.credit}} </td>
             <td> {{this/grade}} </td>
             <td> {{this.contact.mobile}} </td>
          </tr>
        {{/each}}
    </table>
</script>


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 :



<td>
{{#each this.contact}}
{{@key}} :{{this}}<br>
{{/each}}
</td>

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. 🙂


 



Share this

Search

  Recent Posts

  • Creating Installer for Laravel Project

    When you are working on a laravel project there is some basic setup that needs to be done for each install of the project. Like Permissions for ...

  • Laravel Queues With Supervisor

    In this blog, we are going to take a look into Laravel Queues. Queues allow you to defer the processing of a time-consuming task, such as sending a...

  • Partials & Utils in Handlebars

    PARTIALS Let’s say we have a structure like the following : data = { students : [{ name : ‘ABC’, roll : 1 }, { name : ‘DEF&...

See All »

  Recent Tips

See All »

  Recent Seminars

  • PHP 8 - Features

    PHP 8 has been officially released in November 2020! This new major update brings many optimizations and powerful features to the language. This...

  • ProxySQL

    ProxySQL is a high-performance SQL proxy. ProxySQL runs as a daemon watched by a monitoring process. The process monitors the daemon and restarts i...

  • Unix Commands & Shell Scripts to help save our time

    Time is important. We should not waste it doing trivial things. Automate things wherever possible.

See All »