Handlebars – Basic Syntax
by Prabhat Rai

Posted on November 19, 2014 at 08:19 PM


Featured Image

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



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 »