Revisiting JsRender and more: Part I


JsRender is JavaScript library/component/solution which is used for rendering HTML template onto the webpage.

JsRender has been developed by Boris Moore and this is the official JsRender home where you can get latest version and read more.

If you have ever played with any of the client templating solutions like Mustache, hadlebars etc. then JsRender is not so different.

However, JsRender templating is based on string manipulation. That means, unlike other templating solutions, JsRender does the string manipulations first to device the html block which is then inserted into the DOM. wherein, most of the other templating engines, manipulate the DOM content directly making it slower and unpredictable in varying browsers.


I do not claim that JsRender is “the best” templating engine. However, it is certainly the one templating engine which deserves first attention while choosing templating solution for your project.

Lately I have been working with JsRender a lot and it impressed me enough to make me write a blog series about it.

In this first part of the multi-part blog series of JsRender, I will display the basic usage of JsRender and touch upon some advanced topic.

Article Body

May be because of the simplicity of using server controls, not many of the web form projects utilize client side templating. So, most of Web form developers are not aware about JsRender or client templates in general. So, just a short introduction to client templating first.

What is client side templating?

It is the mechanism through which you define the HTML template of the page or section of the page beforehand which could contain some data placeholders. When required, data is fetched from server (ex. using JSON data) and template is used to populate the data at placeholders in the template and then, template is rendered on the page.

This approach gives some of the good advantages over traditional server control oriented web pages; such as,

  • Full control to developers over actual HTML rendered on the page (This is also achieved in MVC apps)
  • Useful when there are lot of sections on the page which keeps updating data.
  • Unlike update panel, only real data is transmitted from server and not HTML.

Note: MVC applications covers most of the advantages from above points. However, by using client templating in MVC application you can still improve performance of page rendering

When to use client templates?

There is no real answer to that question. It is entirely depends on the way page is structured, amount of data and size of page. In fact, there could be lots of pros and cons for using client template in any given scenario and many argue against it.

It is not always good to use client side templating. In scenarios when data to be rendered is too large or the data in template is rarely going to change, it is not beneficial to use templates.

Generally, loading initial page with server side HTML is good idea while using templates to render changed sections on user action.

How to go about JsRender

Please note that, at the time of this writing, JsRender is still in beta. Although, it is fairly stable in recent release if your project requires you to use only released versions then you might want to wait little longer unless you use it in production.

Note: JsRender has been planned to be a official template plugin of jQuery project.

Using JsRender in page is quite easy. You may already know about its basic usage. In the case, you might like to skip this section and read on from the next one.

To make simple client templating to work with JsRender, you will only require following stuff.

reference to JsRender.js file (you can download it from here)

<script type="text/javascript" src="Scripts/jsrender.js"></script>

a template

<script type="text/x-jsrender" id="templateId">
      Welcome {{:UserName}}
      Current server time is {{:ServerTime}}

a JSON data (which may have pulled from server)

data = {
 UserName: "Administrator",
 ServerTime: "6th December 2012"

Now, to use the template and display the JSON data, you need to use render method of JsRender like this


Finally, the rendered template needs to be added as a InnerHTML of some of the container HTML control.

$(“#divContainer”).html($(“#templateId”).render(data) );

Working example with downloadable code

Here goes the complete working example with ajax request to get JSON data and tabular template to display Orders data from Northwind database.

The Default.aspx code with Javascript and use of JsRender

<div id="divOrder"></div>
    <script type="text/javascript" src="Scripts/jsrender.js"></script>
    <script type="text/javascript">
        function GetData() {
              type: "POST",
              url: "Default2.aspx/GetData",
              data: "{}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function (response) {
              error: function (jqXHR, textStatus, errorThrown) {
          return false;

    <script type="text/x-jsrender" id="orderTemplate">
    <table style="color:#333333;background-color:#F7F6F3;border:solid 1px black">
        <thead style="background-color:#5D7B9D;color:white">
        {{for OrderData}}
            <tr><td> {{>OrderID}}</td>
                <td> {{>CustomerID}}</td>
                <td> {{>EmployeeID}}</td>
                <td> {{>OrderDate}}</td>
                <td> {{>RequiredDate}}</td>
                <td> {{>ShippedDate}}</td>
                <td> {{>ShipVia}}</td>
                <td> {{>Freight}}</td>
                <td> {{>ShipName}}</td>
                <td> {{>ShipAddress}}</td>
                <td> {{>ShipCity}}</td>
                <td> {{>ShipRegion}}</td>
                <td> {{>ShipPostalCode}}</td>
                <td> {{>ShipCountry}}</td></tr>

And here is the server side web method GetData

    public static object GetData()
        return new OrderDetailsPage().GetOrders();

    public object GetOrders()
        DataSet ds;
        List<object> record = new List<object>();

        DataService dc = new DataService();
        ds = dc.GetOrders();
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                OrderID = ds.Tables[0].Rows[i]["OrderID"].ToString(),
                CustomerID = ds.Tables[0].Rows[i]["CustomerID"].ToString(),
                EmployeeID = ds.Tables[0].Rows[i]["EmployeeID"].ToString(),
                OrderDate = ds.Tables[0].Rows[i]["OrderDate"].ToString(),
                RequiredDate = ds.Tables[0].Rows[i]["RequiredDate"].ToString(),
                ShippedDate = ds.Tables[0].Rows[i]["ShippedDate"].ToString(),
                ShipVia = ds.Tables[0].Rows[i]["ShipVia"].ToString(),
                Freight = ds.Tables[0].Rows[i]["Freight"].ToString(),
                ShipName = ds.Tables[0].Rows[i]["ShipName"].ToString(),
                ShipAddress = ds.Tables[0].Rows[i]["ShipAddress"].ToString(),
                ShipCity = ds.Tables[0].Rows[i]["ShipCity"].ToString(),
                ShipRegion = ds.Tables[0].Rows[i]["ShipRegion"].ToString(),
                ShipPostalCode = ds.Tables[0].Rows[i]["ShipPostalCode"].ToString(),
                ShipCountry = ds.Tables[0].Rows[i]["ShipCountry"].ToString()
        return new { OrderData = record };

You can also download full example code here (Please note that the sample contains complete code of Part I and Part II of this article series)

More tags

When the JSON data contains raw html and you want to display it as it is – user ‘>’ token


When JSON object contains nested data then use dot operator to indicate the nesting

data = {
  "OrderNumber" : "10090"
  "OrderDetail" : [
       {"ProductId": "1234"},
       {"ProductName": "Printer"}


Use if/else tags for conditional HTML

{{If ShipCountry == 'India'}}
  <span>Shipping country is home country</span>
  <span>Shipping country is foreign country</span>
  Please accept the order by agreeing to the terms
  <input type="button" value="Accept" />

use for loop in case of iterative data which needs to be displayed in the form of list, table etc.

data =  {"OrderData":

example of using for loop in template

<select name="ddlCustomer">
   {{for OrderData}}       
       <option value={{>CustomerID}}> 

External templates

This is all very cool but in any programming concept, template is referred to as something which can be reused just by changing the parameters. That means, we must be able to reuse the same templates.

Also, as I earlier pointed out, use of templating is more viable when there is lot of sections on the page which has variable layout which changes frequently based on user actions.

In such applications, most probably page holds large number of small templates and possibly user does not deals with (open/visits) all sections during every visit. Hence, keeping templates of all sections inside the same page is not very sensible (That will increase overall page size).

JsRender provides another functionality using which we can utilize external templates.

JsRender allows creating templates in JavaScript code on the fly and then displaying JSON data using same template then and there.

var templateString = $.template(‘<div>{{>UserName}}</div>’)

This will create template object just as if it html template is present on the page. This makes it possible to read the content of template from server when required and utilize that template to bind JSON data.

Let us create a new folder in our web site and name it as “Templates”. Then add new file in the folder and move the template code (without script tags) in it. Name the file as CustomerList.template (you may want to add .html extension). The folder structure looks like this

Now, go to success callback event of jQuery ajax request we used earlier. and do following modifications (code lines are fairly commented for understanding)

                type: "POST",
                url: "Default2.aspx/GetData",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    //Provide path of template file on the server
                    var templatePath = 'Templates/customerList.template';
                    //use ajax get method to read template contents 
                    $.get(templatePath, null, function (templateData) {
                        //in the callback event of get method compile named template using callback data
                        var template = $.templates(templateData);
                        //render using compiled template and JSON data from original success callback

Way Ahead

We just reviewed very basics of JsRender and how easy it is to use. JsRender has tons of other features which makes it good candidate for templating engine of your project. some of these are

  • Paths
  • Helper functions
  • Custom tags
  • Converters

I will try to touch upon these advanced topics in next part of this blog series and of course there is also a JsViewes which needs our attention too.

Thanks for visiting! Keep reading.