Saturday 5 July 2014

Databinding using Handlebars js

In this article we are going to see how to create a sample web page using handlebars.js,  For this i am taking the cookbook as sample, one template is written for recipes.


First open a Notepad++, create a html file name first.html and save it under a folder MVC.

Download the Jquery.js from the following link Jquery place inside a folder MVC.
Download  the Handlebars.js from the following link Handlebars place MVC.

Now link the scripts in the Head tag,

<head>
    <script src="jquery-1.11.1.min.js" type="text/javascript"></script>
    <script src="handlebars-v1.3.0.js" type="text/javascript"></script>   
</head>
   

Then create a Handler Template inside a script tag, mention the type as "text/x-handlebars-template".



<script id="sampletemplate" type="text/x-handlebars-template"> 
    <div id="content">
    <center>
    <h1  style="margin-left:10px;color:white">&Xi;RecipeMessages
    <span class="small">Messages search powered by <a id="Logo">   
    </center>
    </h1>
    <div style="margin-left:137px;height:150px:width:100px">
    <img style="color:orange;width:310px" src="images/SplashScreen.png"></img>
    </div>
    {{#each recipes}}
    <div class="" style="float:left;background-color:whitesmoke;
                  padding:10px;margin-left:15px;margin-right:15px">
        <img class="Thumb" src="{{Image}}" alt="{{Name}}"/>
       
       <h3>{{Name}} - 

        <span style="color:orange;font-size:15px">
            {{#if Source}} 
                    {{Source.Name}} 
            {{else}} No  
            {{/if}}
        </span>

        </h3>

        <p style="width:230px">{{Description}}</p>
        <h5 style="color:blue">{{getflavor Flavors}}</h5>

        <h5>{{Yield}}</h5>
        <p>Incredients :</p>
        <ul>
        {{#each Ingredients}}
            <li>{{this}}</li>
        {{/each}}
        </ul>
    </div>
    {{/each}}
    </div>
</script>

From the above template you can notice that double curl braces {{}} the parametere present inside is the exact json property name, and some of keywords are used like #each for foreach iteration of an array, #if for check the condition

Next, Compile the template in the script and bind the data with an anonymous function.



<script>
(function(){

    Handlebars.registerHelper('getflavor',function(flavorcontext){     
        return "This dish has a "+flavorcontext.type+" with "+flavorcontext.flavor+" Flavor.";
    });

    var context ={
        recipes : [
            {  
              "Image":"images/1.jpg",
              "Name":"Briyaani",
              "Description":"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
              "Source":{"Name":"All Recipes"},
              "Flavors":{"type":"Non-Veg","flavor":"Garam"},
              "Yield":"10 pieces of chicken",
              "Ingredients":[ "600 g Ground pork",
                                "1 tsp Salt",
                                "1 tsp sugar",
                                "1/2 tsp Ground black pepper",
                                "2 tsp Cornstarch",
                                "1 tbsp Sesame oil",
                                "1 handful Sliced dried mushrooms ",
                                "soaked and well drained",
                                "18 Quail eggs"                         
                               
                              ]
            },
            {  
              "Image":"images/2.jpg",
              "Name":"Noodles",
              "Description":"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
              "Flavors":{"type":"Veg","flavor":"Sweet"},
              "Yield":"1/2 kg noodles",
              "Ingredients":[ "8 Shrimp",
                                "2 peices of Bread",
                                "1 Egg",
                                "Salt",
                                "4 Tablespoons Soy sauce ",
                                "2 tablespoons Peanut butter ",
                                "1 tablespoon Honey ",
                                "2 teaspoons White vinegar",
                                "1/8 teaspoon Garlipowder",                              
                              ]
            }
        ]
    };
   
   
    var template = Handlebars.compile($('#sampletemplate').html());
    var returnvalue = template(context);
    $('#container').html(returnvalue);

})();
</script>


Above you can see a context is created and binded to the compiled code using handlebars.


Output:








Html:


<!DOCTYPE html>
<html>
<head>
    <script src="jquery-1.11.1.min.js" type="text/javascript"></script>
    <script src="handlebars-v1.3.0.js" type="text/javascript"></script>
   
    <style type="text/css">
      .small{
      font-size:15px;
      color:white;   
      }
      .Thumb
      {
       height:150px;
       width:250px
      }
    </style>
   
</head>
<body>

<div style="background-color:Orange;height:1000px;width:630px" id="container">

</div>
<br />
<input type="button" value="Generate"></input>

<script id="sampletemplate" type="text/x-handlebars-template"> 
    <div id="content">
    <center>
    <h1  style="margin-left:10px;color:white">&Xi;RecipeMessages
    <span class="small">Messages search powered by <a id="Logo">   
    </center>
    </h1>
    <div style="margin-left:137px;height:150px:width:100px">
    <img style="color:orange;width:310px" src="images/SplashScreen.png"></img>
    </div>
    {{#each recipes}}
    <div class="" style="float:left;background-color:whitesmoke;padding:10px;margin-left:15px;margin-right:15px">
        <img class="Thumb" src="{{Image}}" alt="{{Name}}"/>
        <h3>{{Name}} - <span style="color:orange;font-size:15px">{{#if Source}} {{Source.Name}} {{else}} No  {{/if}}</span></h3>
        <p style="width:230px">{{Description}}</p>
        <h5 style="color:blue">{{getflavor Flavors}}</h5>
        <h5>{{Yield}}</h5>
        <p>Incredients :</p>
        <ul>
        {{#each Ingredients}}
            <li>{{this}}</li>
        {{/each}}
        </ul>
    </div>
    {{/each}}
    </div>
</script>

<script>
(function(){

    Handlebars.registerHelper('getflavor',function(flavorcontext){     
        return "This dish has a "+flavorcontext.type+" with "+flavorcontext.flavor+" Flavor.";
    });

    var context ={
        recipes : [
            {  
              "Image":"images/1.jpg",
              "Name":"Briyaani",
              "Description":"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
              "Source":{"Name":"All Recipes"},
              "Flavors":{"type":"Non-Veg","flavor":"Garam"},
              "Yield":"10 pieces of chicken",
              "Ingredients":[ "600 g Ground pork",
                                "1 tsp Salt",
                                "1 tsp sugar",
                                "1/2 tsp Ground black pepper",
                                "2 tsp Cornstarch",
                                "1 tbsp Sesame oil",
                                "1 handful Sliced dried mushrooms ",
                                "soaked and well drained",
                                "18 Quail eggs"                        
                               
                              ]
            },
            {  
              "Image":"images/2.jpg",
              "Name":"Noodles",
              "Description":"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
              "Flavors":{"type":"Veg","flavor":"Sweet"},
              "Yield":"1/2 kg noodles",
              "Ingredients":[ "8 Shrimp",
                                "2 peices of Bread",
                                "1 Egg",
                                "Salt",
                                "4 Tablespoons Soy sauce ",
                                "2 tablespoons Peanut butter ",
                                "1 tablespoon Honey ",
                                "2 teaspoons White vinegar",
                                "1/8 teaspoon Garlic powder",                              
                              ]
            }
        ]
    };
   
   
    var template = Handlebars.compile($('#sampletemplate').html());
    var returnvalue = template(context);
    $('#container').html(returnvalue);

})();
</script>

</body>
</html>



From this article you can see how to create a sample webpage using handlebar js.