Handlebars – Basic Syntax

In this blog we are going to look into basic syntax for writing handlebar templates.

There are 4 steps you need to follow
1. Include jQuery and Handlebars library to your HTML file
2. Define your template.
3. Compiling template into a function, pass data to function and appending it to required HTML element

Include jQuery and Handlebars library to your HTML file
The first step is self explanatory. Handlebars library is a must for running a handlebars program and the handlebars library depends upon jQuery, so include jQuery and Handlebars.

Defining your Template
A handlebars template looks like HTML with having some handlebars expression like {{title}}. Most of the people use handlebars to generate HTML, but it can be easily used to generate  XML, JSON or other text formats.

Whenever we render a handlebars template, Handlebars evaluates the expressions and then replace them with data. Block expressions are used for iteration, conditional statements and executing custom helper functions, but apart from this Handlebars is completely logic less.

Now defining template will have different HTML attributes indentations and if we put them in JS file then it will become hard to read and understand. So handlebars templates can be written inside a script tag, it is a common and a best practice to follow this approach, this is called micro-templating, that means embedding template definition in a tag, with type=”text/x-handlebars-template”, by giving type as handlebars template the browser will not try to execute this code as a script.

Lets see a very basic example which will give you idea of a iterative and conditional statements in handlebars. Lets say we get data for students of class from backend with the detail whether he/she has passed the exams or not. Lets consider that the JSON data we will receive will look like this :

var data = {
    "studentData" : [{
        name : 'ABC',
        roll : 1,
        passed : true
     },{
        name : 'DEF',
        roll : 2,
        passed : false
     },{
        name : 'GHI',
        roll : 3,
        passed : true
    },{
        name : 'JKL',
        roll : 4,
        passed : true
    },{
        name : 'MNO',
        roll : 5,
        passed : false
    },{
        name : 'PQRS',
        roll : 6,
        passed : true
    }]
}

Now we have the requirement to list all the students who have passed the exams. So after seeing the requirements we get 2 things, we have to traverse through the JSON data and then check the field ‘passed‘ to decide whether to show that data or not. So we will try to write this in handlebars template.

First iterating through the data, for this we can use the built-in block helper i.e. the {{each}} helper. You must be wondering what is a block helper. Block helpers make it possible to define custom iterators and other functionality that can invoke the passed block with a new context. [1] We will have a blog on this very soon.
The syntax for a block helper is straight forward. To start a block helper use {{#helpername}} and to finish a block helper use {{/helpername}}. If we use the each helper on studentData then we will achieve our requirement of traversing the object.

{{#each studentData}}
{{!-- 
    {{code here to list the student details}} 
 --}}
{{/each studentData}}

Did you notice something new in above code. {{!– –}} this is used for block comment (multi-line comment). If you want to use single line comment then there is {{!Commented}}.
Proceeding with our template, now the next part here is checking the passed variable. For this we will use {{if}}.

{{#if}}
    {{!-- display the student data here --}}
{{/if}}

To display the data just use the expression with the name of that variable i.e. {{name}}. Lets look at the complete template.

Student Passed in the Exams are : 
<table>
    <tr>
        <th width="60%">Name</th>
        <th width="40%">Roll</th>
     </tr>
     {{#each studentData}}
        {{#if pass}}
           <tr>
              <td>{{name}} </td>
              <td>{{roll}}</td>
           </tr>
        {{/if}}
     {{/each}}
</table>

Compiling template into a function, pass data to function and appending it to required HTML element

Here the first thing is getting the html of the template. For this we will use html() method of jQuery.

html = $('#test_template').html();

Next we have to compile this template string so that it becomes a function.

template = Handlebars.compile(html);

After this a function named template is there, which will take the data as its argument and return us the HTML string. So now we will call this function.

appendText = template(data);

Now we have the required HTML string in variable appendText. Now we just have to put this in the required HTML element. We can use html() or append() etc. depending on our requirement.

$('#test').html(appendText);

Now the HTML element with id test will contain this HTML string. For a working fiddler follow this link.

The next blog will cover the context and blocks. Till then Happy Coding 🙂 .

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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