How to use handlebars js

Here’s one example that summarizes a number of things you can do with handlebars.

(I will post in the near future how to precompile template)

<!--the helper is design to reduce the check in the Template and i can reuse the helper in every place i want -->
<!DOCTYPE html>
    <title>handlebars.js demo</title>
    <!--must have link to jquery -->
    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src="handlebars-v2.0.0.js"></script>
            //here i create helper on my onw, handlebars have there's, this helper reduce the logic in the template
            //register the helper
            Handlebars.registerHelper("checkPrice", function(dataToCheck){
                if(dataToCheck == 20)
                    return "i am 20";
                    return "i another number";

            //get the template html code
            var template = $("#myTemplate").html();

            //handlebars compile the template into a callable function, meaning the render is function
            var render = Handlebars.compile(template);

            //the data i insert, this data can come from server like json or any other option to fetch data
            var result = render({
                //array of object
                "employees" :
                                itemProp: "my cow edna",
                                descriptionProp: "big cow is the best for milk",
                                eatMeet : false,
                                price : 20
                                itemProp: "my cow sharon stone",
                                descriptionProp: "small cow is not best for milk",
                                eatMeet : true,
                                price : 1000

            //call the compiled function with the template data
<!--the template code, here i  use each and if else condition -->
<script id="myTemplate" type="text/x-handlebars-template">
    {{#each employees}}
    <div class="main">
        <h1>the item : {{itemProp}}</h1>
        <h2>the description : {{descriptionProp}}</h2>
        {{#if eatMeet}}
        <h3>she eat meet</h3>
        <h3>she not eat meet</h3>
        <!--the checkPrice is the helper -->
        <h1>{{checkPrice price}}</h1>

<!--the output -->
<div id="output">


link to list of helpers :

This entry was posted in כללי and tagged , , . Bookmark the permalink.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s