Getting Started with jQuery.tmpl (jQuery Templates) in MVC

In this post you will learn how to use jQuery.tmpl (jQuery Template) JavaScript library in MVC for client side templating. I will take you through few easy steps to setup it and working.

There are number of JavaScript templates used these days, some of them works really great. And every JavaScript template library has a slightly different style and syntax and you can pick the library that suits your taste. In my last post “Getting Started with Mustache.js in MVC” I talked about how you can take advantage of Mustache.js library. Now in this post, I will show you some really excellent examples on jQuery.tmpl.


Here is want we are going to create.


You will be able to download the entire code at the end of this article.

Which JavaScript library is better?

As I said, every JavaScript library has slightly different style and syntax so it is completely up to you to select. If you ask me, I absolutely recommend jQuery Templates (jQuery.tmpl), because it is going forward every day. Here are few of the main reasons:
  • Going forward, the massive community support and development around the "official" jQuery solution for templating will be hard to beat.
  • Other than using AJAX requests to load template definitions (which is easy to overcome), jQuery Templates is already as capable as Mustache.js, jTemplates etc. In fact, I think jQuery Templates' {{tmpl}} tag for template composition is more intuitive and straightforward than others like jTemplate uses #include, Mustache also uses {{}}.
  • Another benefit to jQuery Templates is that the data used to populate the template is always available via the .tmplItem() method.
So, these are few reasons recommending jQuery.tmpl over other JavaScript Libraries.

Using jQuery.tmpl in MVC

In MVC Application, we frequently come to scenario where we have to create a view for just displaying small chunk of data and for this jQuery.tmpl is good alternative.

So, let’s create an MVC Application which will display IPL (Indian Premier League) teams and its players suing jQuery.tmpl.

Now, I will take you through step by step from here.

Step 1

Open or Create MVC project and pick empty template or any other template you prefer.

Step 2

Open ‘Manage NuGet Packages’ and search for ‘jquery.templates’ and install it. This will add a ‘jQuery.tmpl’ file in the Script folder. Also install jQuery library if you don’t have.



Step 3

Create following Team and Player model classes:

public class Team
{
    public int TeamId { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    [DataType(DataType.Date)]
    public DateTime Founded { get; set; }

    public virtual ICollection<Player> Players { get; set; }
}

public class Player
{
    public int PlayerId { get; set; }
    public string Name { get; set; }
    public int TotalScored { get; set; }
    public int TeamId { get; set; }

    public virtual Team Team { get; set; }
}

And now generate its CRUD views using Entity Framework and insert records. If you look at above code, I have established one-to-many relationship between both classes hence in both tables.

Here is the data I will be using in this article.


Step 4

Now, add a method ‘TeamAndPlayer’ in Teams controller (or in any other controller) which will return an empty view page.

public ViewResult TeamAndPlayer()
{
    return View();
}

Step 5

Let’s create another method of type ‘JsonResult’, which will return list of Teams and Players.

private IPLContext db = new IPLContext();

public JsonResult RequestData()
{
    var data = db.Teams.ToList();

    var collection = data.Select(x => new
    {
        x.TeamId,
        x.Name,
        x.City,
        x.Founded,
        Players = x.Players.Select(item => new
        {
            item.PlayerId,
            item.Name,
            item.TotalScored,
            item.TeamId
        })
    });

    return Json(collection, JsonRequestBehavior.AllowGet);
}

Till now we implemented every server side codes, let’s develop the view page that will consume these methods.

Step 5

Just add a view page for above TeamAndPlayer method, and add following codes in that view page ‘TeamAndPlayer.cshtml’.


As you can see I have devided complete code into various parts, let’s understand each part one by one.
  1. Referenced the jQuery and jQuery template library.
  2. A button to call the JavaScript function and this function will call the server side method that will return JSON result.
  3. This is actually template structure that jQuery.tmpl library will use to build the DOM. Look at the id ‘teamTemplate’ this is being used in the JavaScript function ‘showTeams’. If you look closely, it has bind attributes enclosed with ${PropertyName} and also {{each Players}}....{{/each}} block that will iterate over nested records.
  4. In the above part we build the DOM structure, now in this part we are just updating the HTML of <tbody id="teamList"></tbody> tag, you can see it clearly in the ‘showTeam’ function $("#teamList").html(....);.
  5. This JavaScript method will calls server side code and gets the JSON result (data) and sends this data to jQuery.tmpl engine and binds it to template.
Step 6

Please note I have used ${GetDate(Founded)} inside template, instead I could have used just ${Founded} like other properties, if so you would have received following output.


And there is quick problem, Founded Date is not well formatted. Now to fix this problem I have used another JavaScript function, this function will transform the jsonDate into user friendly date.

function GetDate(jsonDate) {
    var value = new Date(parseInt(jsonDate.substr(6)));
    return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear();
}

So, the complete template code will be as follows:

<script id="teamTemplate" type="text/html">
    <tr>
        <td>${Name}</td>
        <td>${City}</td>
        <td>${GetDate(Founded)}</td>
        <td>
            <ol>
                {{each Players}}
                    <li>${$value.Name} - ${$value.TotalScored} Runs</li>
                {{/each}}
            </ol>
        </td>
    </tr>
</script>

So, now we are all set to run the application, just click the button and you will get following output.


Step 6

In case if you want to separate the players name with ',' and 'and' as given below, just use the upcoming code.

And here is the code:

<script id="teamTemplate" type="text/html">
    <tr>
        <td>${Name}</td>
        <td>${City}</td>
        <td>${GetDate(Founded)}</td>
        <td>
            {{each Players}}
                ${$value.Name}{{if $index < Players.length - 2}}, {{else $index === Players.length - 2}} and {{/if}}
            {{/each}}
        </td>
    </tr>
</script>

Sweet. Very quick and smaller payloads.


Thanks for reading.

Hope this helps.

Comments

  1. Knockout already have foreach which internally take care of whatever you just shown. (Without adding extra JS Library)

    ReplyDelete
    Replies
    1. My friend I moderated your comment, just because to answer you. I am big big fan of Knockout.js, but if you look at this blog, you will notice I'm not adding anything new, I only have shown which is already there. If you think, I have added extra JS then go and ask why other JS library available like Mustache etc? I think I answered you. For your kind information, jQuery.tmpl is one of the Microsoft recommended client side templating library, if you remember.

      Delete
  2. Thanks for this. It's a good start....

    ReplyDelete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System