JsRender, a new way to render HTML

Introduction

JsRender is the new Jquery library; with the help of this library we can render Client Side Templates.

Step 1: First of all we will create a new web application with a Blank template:
 
First.png

Step 2:
Now we will add Script and View Folders.

Step 3: Now will to the nuget.org site and install the Jang.JsRender for Jsrender.js file.
 
seconf.png
 
We will use the PM> Install-Package Jang.JsRender command to install Jang.JsRender. 
 
Step 4: Now in the View folder we will add one HTML page. in that page we will add JsRender.js:
 
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"/>
 <
script src="../Scripts/jsrender.js" type="text/javascript"/>

Step 5: Now we will create a Json array collection for the Customer Object:
 
 <script language="ecmascript" type="text/javascript">
     var my = my || {};
     my.getCustomer = function () {
         return [
         { "ID": "1", "Name": "Bobby Jones", "Birthday": "1902-03-17" },
         { "ID": "2", "Name": "Sam Snead", "Birthday": "1912-05-27" },
         { "ID": "3", "Name": "Tiger Woods", "Birthday": "1975-12-30" }
         ];
     };

 </
script>
 
Step 6: Now we will add actual templates which will render on the UI:
 
<div id="GolferDiv">
 </
div>

The above DIV is the main container where we will add the 
following HTML template which will render inside the GolferDiv Container.
 
You can see that in the following template we simply fire a for loop for the Customer Array:
 
<script id="GolferTemplate1" type="text/x-jsrender">
 <div>{{:customer.length}} customer found</div>
        <ul>
 {{for customer tmpl="#InnerGolferTemplate1"/}}
 </ul>

 </
script>
  

 <
script id="InnerGolferTemplate1" type="text/x-jsrender">
         {{:ID}}: <b>{{:Name}}</b> <i>{{:Birthday}}</i> <br />

 </
script>
 <
br />  
  

 <
script type="text/javascript">
     $(document).ready(function () {
         my.vm = {
             customer: my.getCustomer()
         };
         $("#GolferDiv").html($("#GolferTemplate1").render(my.vm));
     });

 </
script>
 
Step 7: Now to run our application and see the output:
 
third.png
Happy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all