Getting Started With Mustache.js in MVC

In this article you will learn how to use the Mustache.js JavaScript library in MVC for client-side templating.  I will take you through the easy procedure of its setup it and how it works.

There are many JavaScript template libraries to choose from these days like Handlebars.js, Dust.js, Google's Closure Templates and so on, these all are known as logic-less templates. I recommend you read this article.

So, every JavaScript template library has a slightly different style and syntax and you can choose the library that suits your tastes. All the libraries provide functionality similar to Razor, in the sense you have HTML markup and then placeholders with special delimiters where the data is to appear. These placeholders are called binding expressions.

In a MVC Application, we frequently encounter the scenario where we need to create a view to just display a small chunk of data. So, let's create an application that will display name, address and mobile number. I will take you through the procedure from here.

Step 1: Open or create a MVC project with empty template or any template you prefer.

Step 2: Open "Manage NuGet Packages" and search for "mustache.js" and install it. This will add a "mustache.js" file in the Script folder. Also install the jQuery library if you don't have.

Step 3: Add any controller and its associated view or open it if you already have it. In my case, I had a "Home" controller and an "Index" view.

Step 4: Add a model class with appropriate properties, here is what will be using.

public class Friend
{
   
public int Id { get; set; }
   
public string Name { get; set; }
   
public string Address { get; set; }
   
public string Mobile { get; set; }
}

Step 5: Implement a method returning JSON data, maybe in your controller. Here is my Index view method and a method "MyFriends".

public ActionResult Index()
{
   
return View();
}
public JsonResult MyFriends()
{
   
List<Friend> friends = new List<Friend>();
    friends.Add(
new Friend { Name = "Deepak", Address = "Bokaro", Mobile = "9966453241" });
    friends.Add(
new Friend { Name = "Rohit", Address = "Dhanbad", Mobile = "5454544533" });
    friends.Add(
new Friend { Name = "Ram", Address = "Dumka", Mobile = "4456576589" });
    friends.Add(
new Friend { Name = "Shyam", Address = "Ranchi", Mobile = "9876543456" });
    friends.Add(
new Friend { Name = "Mohan", Address = "Giridih", Mobile = "9876567439" });
   
return Json(friends, JsonRequestBehavior.AllowGet);
}

We are now done with server-side implementations, this is what you normally do. From here we wil implement the Mustache template.

Step 6: Add a reference for jQuery and Mustache in the view page.

<script src="~/Scripts/jquery-2.0.3.min.js"></script>

<script src="~/Scripts/mustache.js"></script>

Step 7: Add a JavaScript method "showFriends" that will call the server-side "MyFriends" method returning JSON data.

<script type="text/javascript">
    function showFriends(e) {
        $.getJSON(
"MyFriends", function (data) {
           
var templateWithData = Mustache.to_html($("#templateFriends").html(), { RootTag: data });
            $(
"#destinationElement").empty().html(templateWithData);
        });
    }
</script>

In the code above, Mustache.to_html($("#templateFriends") is the magical code that maps to the template with data (that we will create in the next step) and that updates the DOM element by the id "destinationElement". Remember I have assigned the "data" in "RootTag" (this can be any name), so this will be used in the template as a Root tag. Now there are three things remaining to be done, i) create the template that can be of any format list, table or whatever you wish, ii) create a DOM element by the id "destinationElement" and iii) generate an event to call the "showFriends" method, in my case I will use a button.

Step 8: Here is a button to generate the function call, and a DOM element to update and a template format (tabular), in the next step I will show you the list template of it.

<input type="button" value="Show Data" onclick="showFriends();" />
<
div id="destinationElement">
</
div>
<
script id="templateFriends" type="text/html">
    <table>
        <thead>
            <th>Name</th>
            <th>Address</th>
            <th>Mobile</th>
        </thead>
        {{#RootTag}}
            <tr>
                <td>{{Name}}</td>
                <td>{{Address}}</td>
                <td>{{Mobile}}</td>
            </tr>
        {{/RootTag}}
    </table>
</
script>

In the code above, the script tag has the type text/html and because of this the JavaScript rendering system (in the user's browser) will not interpret it as a script and execute it. Also there is the binding of the properties between the double braces, the RootTag has all the data to be assigned in the internal properties Name, Address and Mobile. Here is what you will see as output.

tabular.png
 

Step 9: If you want to list the data rather than showing it in tabular format, you just do it by replacing the code above with the following.

<input type="button" value="Show Data" onclick="showFriends();" />
<
div id="destinationElement">
</
div>
<
script id="templateFriends" type="text/html">
    <ul>
        {{#RootTag}}
            <li>{{Name}} - {{Address}} - {{Mobile}}</li>
        {{/RootTag}}
    </ul>
</
script>

list.png
 

And that's it.

You can download the source code from here.

Hope this helps.

Next Recommended Readings