Saturday 5 July 2014

HandleBars in Asp.Net MVC

In this article we are going to see the Handlebars.js in asp.net mvc, Handlebars js is a compiler which compiles the Templated script , and Binds the data passes to the Template, return back the result along with binding. Let we see how to use it.

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">
    <h1 style="margin-left:10px">&Xi;RecipeMessages
    <span class="small">Messages search powered by <a id="Logo">

                        <img  style="height:15px" src='https://encrypted-tbn2.gstatic.com/images?                                                       q=tbn:ANd9GcQmN4Hz1m2z4hoqhQtyywvPl7GkxDHUNt9OJDZZvBN7_uNmBZFw'/>                 </a>
           </span>
    </h1>
    </div>
</script>

Next, Create a script which will bind the template with data, from the above template i didnt pass any data to bind , so just compile the template and assign the value to the div container.


<script>
(function(){

    var template = Handlebars.compile($('#sampletemplate').html());
    var returnvalue = template();
    $('#container').html(returnvalue);

})();
</script>



From the script you can see the Handlebars.compile which will compile the template, in the next line template(), where we have to pass the data context to bind the template,

Final output will be like this . . .



Html:

<style type="text/css">
      
.small{
      font-size:15px;
      color:white;;
      }
    
</style>
   


<div style="background-color:rgb(94,170,222);height:300px;width:500px" id="container">

</div>



From this article you can learn some basics of Handle bars with out data context.


  

No comments:

Post a Comment