Using Mustache.js for Templating
Posted by: Suprotim Agarwal ,
on 9/17/2015,
in
Category jQuery and ASP.NET
Abstract: Mustache.js is a logic-less templating library, which supports the philosophy of little or no logic in your HTML templates. We will see a simple example of using this library to read a JSON file.
One of the central tenets of modern web development is the separation of structure/content from behavior, a.k.a separate view from code. In our projects, we either tend to craft our HTML elements using string processing and concatenation; or build elements using native DOM methods, and then insert these elements into the DOM. However as the size and complexity of a project grows, it leads to spaghetti code. Maintainability becomes an issue in such cases.
Templates can be beneficial here as templates simplify the entire process, increase reusability and minimize the amount of code needed to generate HTML elements from data.
Mustache.js (http://mustache.github.io/) is a logic-less templating library, which essentially supports the philosophy of little or no logic in your HTML templates. That means in your templates, there are no loops or if-else statements; instead there are only tags. There are several other logic-less templates out there like dust.js, handlebars.js etc. which provide more functionality. We even have jQuery templating libraries like jQuery Templates and jsViews, which have been deprecated and superseded by the jsRender project. However we are choosing Mustache.js for our example as I find it very simple to use, and moreover we do not require too much complexity in this example. Having said that, feel free to look into the other templating engines too and decide what's best for your project.
The premise of Mustache.js is quite simple. Think of it as a blueprint of HTML markup which lets you flow data on a page. You can use as many templates as you want on a page, and take the same data and display it in different ways.
To get started, you can either download the Mustache library from Github https://github.com/janl/mustache.js or use a CDN from cdnjs.com.
In this example, we will read JSON data containing author information and display it on a page using Mustache template. The .json file is kept in the ‘scripts’ folder. The structure of the JSON data is as follows:
Note: Make sure your JSON is valid. Use a JSON validator like jsonlint.com to validate your JSON.
There are various methods for defining mustache templates in your application, like using it inline or using it as external templates. For our example, we will create it inline but for better maintainability, you should make it a practice of keeping it in a separate file for your applications. So if you decide to keep the template in a separate file, all you have to do is create a <templatename>.js file and then add a reference to this file using the <script> tag
<script src="../scripts/templatename.js"></script>
Coming back to our example, create a new page called ‘Mustache.html’. Our template is called authortmpl and we will define template data inside of a <script> tag with a MIME type of text/template.
<script id="authortmpl" type="text/template">
</script>
Note: We are using a MIME type other than text/javascript, to prevent the browser from executing the template code.
First off, we will start by creating a placeholder for authors. This is done using brace characters ({}) which looks like sideway mustaches (hence the name mustache.js).
<script id="authortmpl" type="text/template">
{{#authors}}
{{/authors}}
</script>
Observe how we are closing the authors placeholder using a backslash (/). This is similar to what we do with HTML elements. If you observe, authors is the name of the object in our JSON data file authorslist.json. Mustache.js cycles through all the authors in that object and applies the template that is defined here.
<script id="authortmpl" type="text/template">
{{#authors}}
<div class="divwrap">
<h2>{{name}}</h2>
<img src="images/{{image}}" alt="{{name}}" class="imgwrap"/>
<p class="pwrap">{{bio}}</p>
<p>Twitter: {{twitter}}</p>
</div>
{{/authors}}
</script>
In the template, we have a <div> with a class ‘divwrap’ and the author name, image, bio and Twitter handler defined inside the <div>. Image and the paragraph have been decorated with the ‘imgwrap’ and ‘pwrap’ classes respectively. This is to beautify the template with CSS. The css file ‘templ.css’ is kept in the ‘css’ folder. We have added a reference to this css file inside the <head> section of the HTML file..
<link href="css/templ.css" rel="stylesheet" />
templ.css
.divwrap {
width:500px;
border-bottom: 3px solid #4588ba;
margin-bottom:10px;
font: 14px Georgia, serif;
}
.imgwrap {
float:left;
margin:5px;
}
.pwrap {
height: 100px;
background: #4679bd;
padding: 5px 60px;
color: #fff;
border-radius: 9px;
font-style: italic;
}
Let's go back to the script. If you observe the script, the tags defined inside the double braces match the elements in our .json file. Eg: {{name}} acts as placeholder which targets the name element inside the .json file and so on. Overall this template is nothing more than some html and placeholders. As you can see, it is a logic-less template; there are no programming blocks, if-else statements or any loops.
Finally we need to use jQuery to grab our authorslist.json file and insert the data into our template. We will use jQuery’s $.getJSON() method to load JSON-encoded data from the server using a GET HTTP request.
Note: For a refresher article on jQuery ajax and getjSON, check https://www.dotnetcurry.com/jquery/1093/jquery-ajax-basics and https://www.dotnetcurry.com/jquery/1095/json-jsonp-jquery-basic-tutorial
$.getJSON('scripts/authorslist.json', function (data) {
var templ = $('#authortmpl').html();
var mustch = Mustache.to_html(templ, data);
$("#authorlist").html(mustch);
});
Here the $.getJSON() function loads the data file authorlist.json and executes a function literal to read the contents of the JSON file, into a data object. A variable called templ loads the content of the authortmpl template that we created a short while ago. We then use the Mustache.to_html() method and pass the template and JSON data as parameters. Moustache will process the data and feed it into the template and create some HTML for us that we load in an authorlist div.
Save the HTML file and view it in a browser. Here’s the output:
Conclusion
We saw a beautiful logicless template syntax made possible using the Mustache.js library. You can even use this library for config files and source code. Different implementations of this library is available for different language syntax as well, for eg: PHP, Ruby, Python and many more as listed over here http://mustache.github.io/. Thanks to Chris Wanstrath (GitHub CEO) and his team for creating it!
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn