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.

  1. public class Friend  
  2. {  
  3.     public int Id { getset; }  
  4.     public string Name { getset; }  
  5.     public string Address { getset; }  
  6.     public string Mobile { getset; }  
  7. }  

 

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

  1. public ActionResult Index()  
  2. {  
  3.     return View();  
  4. }  
  5. public JsonResult MyFriends()  
  6. {  
  7.     List<Friend> friends = new List<Friend>();  
  8.     friends.Add(new Friend { Name = "Deepak", Address = "Bokaro", Mobile = "9966453241" });  
  9.     friends.Add(new Friend { Name = "Rohit", Address = "Dhanbad", Mobile = "5454544533" });  
  10.     friends.Add(new Friend { Name = "Ram", Address = "Dumka", Mobile = "4456576589" });  
  11.     friends.Add(new Friend { Name = "Shyam", Address = "Ranchi", Mobile = "9876543456" });  
  12.     friends.Add(new Friend { Name = "Mohan", Address = "Giridih", Mobile = "9876567439" });  
  13.     return Json(friends, JsonRequestBehavior.AllowGet);  
  14. }  

 

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.

 

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

 

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

  1. <script type="text/javascript">  
  2.     function showFriends(e) {  
  3.         $.getJSON("MyFriends"function (data) {  
  4.             var templateWithData = Mustache.to_html($("#templateFriends").html(), { RootTag: data });  
  5.             $("#destinationElement").empty().html(templateWithData);  
  6.         });  
  7.     }  
  8. </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.

  1. <input type="button" value="Show Data" onclick="showFriends();" />  
  2. <div id="destinationElement">  
  3. </div>  
  4. <script id="templateFriends" type="text/html">  
  5.     <table>  
  6.         <thead>  
  7.             <th>Name</th>  
  8.             <th>Address</th>  
  9.             <th>Mobile</th>  
  10.         </thead>  
  11.         {{#RootTag}}  
  12.             <tr>  
  13.                 <td>{{Name}}</td>  
  14.                 <td>{{Address}}</td>  
  15.                 <td>{{Mobile}}</td>  
  16.             </tr>  
  17.         {{/RootTag}}  
  18.     </table>  
  19. </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.

  1. <input type="button" value="Show Data" onclick="showFriends();" />  
  2. <div id="destinationElement">  
  3. </div>  
  4. <script id="templateFriends" type="text/html">  
  5.     <ul>  
  6.         {{#RootTag}}  
  7.             <li>{{Name}} - {{Address}} - {{Mobile}}</li>  
  8.         {{/RootTag}}  
  9.     </ul>  
  10. </script>  

 

list.png
 

And that's it.

You can download the source code from here.

Hope this helps.