Rendering objects using Handlebars

Handlebars is a template language that adds minimal syntax to HTML. Its goal is to minimize the amount of logic present in the template and force the passed model object to correspond to what should be rendered in the view.

In this recipe, we will demonstrate some of the advantages and shortcomings of Handlebars using a simple example. We're going to render a user greeting based on the time of the day.

Getting ready

We need to download Handlebars from https://github.com/wycats/handlebars.js. The browser version is in the dist directory. Create a directory for the example and copy handlebars.js to this directory, or download directly (on Linux):

wget https://raw.github.com/wycats/handlebars.js/master/dist/handlebars.js

How to do it...

Let's write the code:

  1. Create index.html containing a name input, a greeting placeholder, and the Handlebars template:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Displaying objects with Handlebars</title>
    </head>
    <body>
    <form method="post">
        <p>Name: <input id="name" type="text" name="name" value="John"></p>
    </form>
    <div id="greeting">
    </div>
    <script id="template" type="text/x-handlebars-template">
    
    {{#if evening}}
        Good evening,
    {{/if}}
    {{#if morning}}
        Good morning,
    {{/if}}
    {{#if day}}
        Hello,
    {{/if}}
    <b>{{name}}</b>
    
    </script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="handlebars.js"></script>
    <script type="text/javascript" src="example.js"></script>
    </body>
    </html>
  2. Create example.js to bind the template to the data and the view:
    $(function() {
        var template = Handlebars.compile($('#template').html());
        function changeName() {
            var hour = new Date().getHours();
            $('#greeting').html(template({
                name: $("#name").val(),
                evening: hour > 18,
                morning: hour < 10,
                day: hour >= 10 && hour <= 18
            }));
        }
        $('#name').on('keypress keyup', changeName);
        changeName();
    });

How it works...

We usually embed Handlebars templates inside an HTML page by adding them to a script element with a type attribute set to text/x-handlebars-template. The browser ignores scripts with unknown types, so we can be sure that the content is left intact.

Using the template is done in two phases. In the first phase, we need to compile the template text. This process results with a compiled template in the form of a JavaScript function being returned. In the second phase, we pass a model object as a parameter to that function (the compiled template) and get the HTML output.

Handlebars is a very opinionated and minimal templating language. The use of program logic, such as comparison operators inside the template is strictly forbidden. This is by design, and it is a good idea, if the business logic changes we don't need to update the template. For example, if we start considering the period from midnight to 2 a.m. as evening, we don't need to change the template – we only need to add the condition when creating the model, which we pass to Handlebars.

On the other hand, we can see that Handlebars sometimes goes a bit too far with its restrictions. For example, it doesn't support a case structure, enumerations or constructs such as 'else if'. As a result, we must either resort to Boolean expressions for every possible state or keep the actual text or value inside the model. In some of those cases the model may interfere with information that belongs to the view.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.185.196