Tutorial: HTML Templates with Mustache.js

}

When developing modern HTML applications, you often write a lot of HTML fragments programmatically. You concatenate HTML tags and dynamic data, and insert the resulting UI markup into the DOM. Here is a random code example of this approach:

$.each(messages.reverse(), function(index, message) {
	$('#messageList').append(
		'<li><span class="list-title">' +
		message.userName + '</span>' +
		'<abbr class="list-timestamp" title="' +
		message.datePosted + '"></abbr>' +
		'<p class="list-text">' + message.messageText + '</p></li>');
	}
});

The proliferation of this kind of code throughout your application comes with some downsides. The tight coupling of UI and data logic doesn’t promote separation of concerns and reuse. It makes your application harder to write and harder to maintain.

HTML templates address this issue by decoupling the UI definition (HTML markup) from the data. There are a number of HTML template solutions out there: jQuery Templates, Underscore.js, and Mustache.js to name a few. Mustache.js is a popular choice because of its powerful syntax and fast rendering.

Mustache is a “logic-less” template syntax. “Logic-less” means that it doesn’t rely on procedural statements (if, else, for, etc.): Mustache templates are entirely defined with tags. Mustache is implemented in different languages: Ruby, JavaScript, Python, PHP, Perl, Objective-C, Java, .NET, Android, C++, Go, Lua, Scala, etc. Mustache.js is the JavaScript implementation.

In this article, we take a quick tour of some of the capabilities of Mustache.js.

To start using Mustache.js, simply add a script tag to your html file pointing to mustache.js which is available here.

You can run all the examples below here.

Sample 1: Basic Template

This is a self-explanatory example. Note that:

  • Instead of being defined in a variable, the data often comes from a service call (see sample 2)
  • Instead of being defined in a variable, the template is often read from a file (see sample 3)
	var person = {
		firstName: "Christophe",
		lastName: "Coenraets",
		blogURL: "http://coenraets.org"
	};
	var template = "<h1>{{firstName}} {{lastName}}</h1>Blog: {{blogURL}}";
	var html = Mustache.to_html(template, person);
	$('#sampleArea').html(html);

Result:

Christophe Coenraets

Blog: http://coenraets.org

 

Sample 2: Basic Template using Ajax data

Same as sample 1, except that we get the data from an Ajax service call.

$.getJSON('json/data.json', function(data) {
	var template = "<h1>{{firstName}} {{lastName}}</h1>Blog: {{blogURL}}";
	var html = Mustache.to_html(template, data);
	$('#sampleArea').html(html);
});

Result:

John Smith

Blog: http://johnsmith.com

 

Sample 3: Externalized Template

Same as sample 2, except that we read the template from the main HTML file.

$.getJSON('json/data2.json', function(data) {
	var template = $('#personTpl').html();
	var html = Mustache.to_html(template, data);
	$('#sampleArea').html(html);
});

The template is defined as follows in index.html:

<script id="personTpl" type="text/template">
<h1>{{firstName}} {{lastName}}</h1>
<p>Blog URL: <a href="{{blogURL}}">{{blogURL}}</a></p>
</script>

Result:

Lisa Jones

Blog URL: http://lisajones.com

 

NOTE: Sample 3 represents the way templates are being used in many dynamic Web applications:

  • You get data from an Ajax service
  • You read the template from an external file

In the remaining of this article, we declare the data and the template in variables to keep the examples self-contained. Remember to refer to sample 3 for a traditional setup when using templates in a dynamic Web application.

 

Sample 4: Enumerable Section

var data = {name: "John Smith", skills: ['JavaScript', 'PHP', 'Java']};
var tpl = "{{name}} skills:<ul>{{#skills}}<li>{{.}}</li>{{/skills}}</ul>";
var html = Mustache.to_html(tpl, data);
$('#sampleArea').html(html);

Result:

John Smith skills:
  • JavaScript
  • PHP
  • Java

 

Sample 5: Enumerable Section with Objects

var data = {
	employees: [
	{	firstName: "Christophe",
		lastName: "Coenraets"},
	{	firstName: "John",
		lastName: "Smith"}
	]};
var template = "Employees:<ul>{{#employees}}" +
                            "<li>{{firstName}} {{lastName}}</li>" +
                            "{{/employees}}</ul>";
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);

Result:

Employees:
  • Christophe Coenraets
  • John Smith

 

Sample 6: Nested Objects

You can use the dot notation to access object properties.

var person = {
	firstName: "Christophe",
	lastName: "Coenraets",
	blogURL: "http://coenraets.org",
	manager : {
		firstName: "John",
		lastName: "Smith"
	}
};
var template = "<h1>{{firstName}} {{lastName}}</h1><p>{{blogURL}}</p>" +
               "Manager: {{manager.firstName}} {{manager.lastName}}";
var html = Mustache.to_html(template, person);
$('#sampleArea').html(html);

Result:

Christophe Coenraets

http://coenraets.org

Manager: John Smith

 

Sample 7: Dereferencing

Same as sample 6, except that we “dereference” the manager object to make it easier to access its properties (without having to use the dot notation).

var person = {
	firstName: "John",
	lastName: "Smith",
	blogURL: "http://johnsmith.com",
	manager : {
		firstName: "Lisa",
		lastName: "Jones"
	}
};
var tpl = "<h1>{{firstName}} {{lastName}}</h1><p>{{blogURL}}</p>" +
          "{{#manager}}Manager: {{firstName}} {{lastName}}{{/manager}}";
var html = Mustache.to_html(tpl, person);
$('#sampleArea').html(html);

Result:

John Smith

http://johnsmith.com

Manager: Lisa Jones

 

Sample 8: Function

Templates can reference functions like totalPrice in this example.

var product = {
	name: "FooBar",
	price: 100,
	salesTax: 0.05,
	totalPrice: function() {
		return this.price + this.price * this.salesTax;
	}
};
var template = "<p>Product Name: {{name}}</p>Price: {{totalPrice}}";
var html = Mustache.to_html(template, product);
$('#sampleArea').html(html);

Result:

Product Name: FooBar

Price: 105

 

Sample 9: Condition

Templates can include conditional sections. Conditional sections only render if the condition evaluates to true. A conditional section begins with {{#condition}} and ends with {{/condition}}. “condition” can be a boolean value or a function returning a boolean.

var data = {
	employees: [
	{	firstName: "Christophe",
		lastName: "Coenraets",
		fullTime: true,
		phone: "617-123-4567"
	},
	{	firstName: "John",
		lastName: "Smith",
		fullTime: false,
		phone: "617-987-6543"
	},
	{	firstName: "Lisa",
		lastName: "Jones",
		fullTime: true,
		phone: "617-111-2323"
	},
	]};
var tpl = "Employees:<ul>{{#employees}}<li>{{firstName}} {{lastName}}" +
          "{{#fullTime}} {{phone}}{{/fullTime}}</li>{{/employees}}</ul>";
var html = Mustache.to_html(tpl, data);
$('#sampleArea').html(html);

Result:

Employees:
  • Christophe Coenraets 617-123-4567
  • John Smith
  • Lisa Jones 617-111-2323

 

Sample 10: Partials

var data = {
	firstName: "Christophe",
	lastName: "Coenraets",
	address: "1 Main street",
	city: "Boston",
	state: "MA",
	zip: "02106"
};

var template = "<h1>{{firstName}} {{lastName}}</h1>{{>address}}";
var partials = {address: "<p>{{address}}</p>{{city}}, {{state}} {{zip}}"};
var html = Mustache.to_html(template, data, partials);
$('#sampleArea').html(html);

Result:

Christophe Coenraets

1 Main street

Boston, MA 02106

 

Sample 11: Partials in Enumerable Section

var data = { depts: [
	{	name: "Engineering",
		employees: [
			{firstName: "Christophe", lastName: "Coenraets"},
			{firstName: "John", lastName: "Smith"}]
	},
	{	name: "Sales",
		employees: [
			{firstName: "Paula", lastName: "Taylor"},
			{firstName: "Lisa", lastName: "Jones"}]
	}]
};

var tpl = "{{#depts}}<h1>{{name}}</h1>" +
          "<ul>{{#employees}}{{>employee}}{{/employees}}</ul>{{/depts}}";
var partials = {employee: "<li>{{firstName}} {{lastName}}</li>"};
var html = Mustache.to_html(tpl, data, partials);
$('#sampleArea').html(html);

Result:

Engineering

  • Christophe Coenraets
  • John Smith

Sales

  • Paula Taylor
  • Lisa Jones

 

You can run all the examples here.

 

61 Responses to Tutorial: HTML Templates with Mustache.js

  1. Chris January 6, 2012 at 8:37 am #

    Thanks for this post. It’s an excellent cheat sheet for mustache! Much appreciated.

  2. Omar Abdallah January 12, 2012 at 2:38 pm #

    Pretty nice engine, was looking for something like that, thanks alot

  3. Larry January 23, 2012 at 4:47 am #

    Do you have an example of doing recursion? I have an object like this:
    { “name”: “bob”,
    “friend”: [{"name": "luke"},
    {"name": "steve",
    "friend": [{"name": "Pat"},
    {"name": "Dave"}
    ]}
    ]}

    I want to see them in a list like this:
    bob
    luke
    steve
    Pat
    Dave

    • Larry January 23, 2012 at 4:49 am #

      That didn’t show up very good I want to see the output like this:
      bob
      —–luke
      —–steve
      ———Pat
      ———Dave

  4. Victor February 21, 2012 at 9:51 pm #

    Nice work! Help me a lot! thanks

  5. Jan March 9, 2012 at 6:41 pm #

    Is putting templates in tags as mentioned in sample3 supported in vanilla Mustache?
    I’m asking, because I was under the impression that this you would need something like ICanHaz.js for this.

    It’s great if Mustache supports this out-of-the-box, since ICanHaz is signicantly slower. At least for what I have been using it for.

  6. Bill Heaton March 10, 2012 at 11:47 pm #

    I keep coming back to this article and sending other to so the same when learning Mustache. The examples are source code are great, thanks.

  7. Chintan March 29, 2012 at 9:36 pm #

    Is there a way in Mustache to get the index of element in array?

  8. alex April 4, 2012 at 10:36 am #

    Here’s an example how to separate the templates from the rest of the code:

    {{title}}

    {{content}}

    var template = $(‘#template1′).html();

    Cheers!

  9. miss Red April 10, 2012 at 8:51 pm #

    very usefull. i m trying to figure out whats abbout jvs

  10. Joe May 1, 2012 at 4:45 pm #

    What is the difference between mustache.render and mustache.to_html? Can’t seem to find this info anywhere.

  11. Yasin Coşkun May 24, 2012 at 11:24 am #

    nice tutorial thanx

  12. Landon June 11, 2012 at 9:03 pm #

    I am working on a project that uses brunch.io and mustache for templating. I want to add mustache partials to the main index (which serves as a ‘shell’) to load in my content. I create the mustache partials in their own .mustache file and then add the tag on the index page (ie: {{> somePartial}} ) but what I seem to be missing is how to get the partial to render… Thats what I need help with.

  13. madhuka June 19, 2012 at 9:45 am #

    Thanks, good post

  14. raj June 21, 2012 at 6:03 am #

    Hi how can we handled xml value say my json value is
    var person = {
    key : (value is xml )
    raj
    dugar

    }
    };

    how can i get only value of tag i.e dugar from this json repsonse using template

    any help will be appreciated

  15. Nitesh July 28, 2012 at 6:07 pm #

    You explained all cases… really helped

  16. mauro September 3, 2012 at 12:58 pm #

    Hey thanks for the tutorial! I have a question. How can I load and append in the body tag a Mustache template which is another folder of my website using jQuery?

    • David January 14, 2013 at 1:18 pm #

      $.get(url, function(data) {
      var template = data;
      var html = Mustache.to_html(template, person);
      $(‘#sampleArea’).html(html);
      });

  17. Kumaresan September 20, 2012 at 11:45 am #

    This post was very useful. We need one more use case. I want display the html content or render the HTML content in the document.

    for Example:

    Here is the sample obj.

    var obj = {
    fName: “Kumaresan”,
    lName:”",
    Ph:”1234″,
    Photo: “”
    }

    I want to display the output is given below:

    1. First Output :
    ————– Kumaresan,

    ————– 1234,

    2. Second Output:

    First Name : “Kumaresan”
    Last Name : “”
    Phone : “1234″
    Photo Url :

    How to write a template for above output?

    Thanks,
    Kumaresan.

    • Kumaresan September 20, 2012 at 11:48 am #

      The actual value for “Photo Url” : <img src=”<Phot_url>” />

      • narun December 8, 2012 at 5:50 am #

        test

  18. Manikandan Ganesan October 5, 2012 at 1:46 pm #

    Quick kick starter for using Mustache and thanks for sharing such a useful tips!

  19. Partha Das October 17, 2012 at 6:16 pm #

    Is it possible to implement paging and sorting with mustache.js??

  20. Tejas Nityanand November 1, 2012 at 1:45 pm #

    Hey,
    Very useful tutorials. I have been looking for the implementation of Mustache, and your blog explains it well. I have one problem though, I tried the ‘Sample 2: Basic Template using Ajax data’ but in my case when I view the page I am getting an error in the Firefox Error Console saying: ‘not well-formed’ pointing to the JSON file.
    I have used the exact same code as shown in the sample.

    • Bardh Lohaj July 27, 2013 at 9:34 am #

      Even that this response seems too late, I was thinking hat it may be good for someone.

      The ‘not well-formed’ console error in my case was displayed because my mustache files where not properly formed. The error can be because of a not properly closed html tag, double quotes within an mustache if condition like {{#condition}} checked=”checked” {{/condition}}, not properly closed attribute for example class=”asd etc.

  21. Bas Velthuizen November 14, 2012 at 7:48 pm #

    Hello,

    Strangely enough, the code in your tutorial is rendered wrong in both firefox and chrome.
    All html-tags of the beautified code are visible and html-encoded. I don’t think that is meant to be, because they are completely unreadable.
    Is this a setting in my browsers, or has something changed lately in the libraries that are used?

    Cheers,
    Bas

  22. Minerva December 29, 2012 at 12:06 pm #

    Hello! Someone in my Facebook group shared this site
    with us so I came to take a look. I’m definitely enjoying the information. I’m
    bookmarking and will be tweeting this to my followers! Superb blog and superb design.

  23. social media for small business infographic January 12, 2013 at 2:24 am #

    You must give your marketing methods to be able to work.

    In this field, the Australian Institute of Internet Marketing helps people a lot.
    This really is also advantageous too simply because if someone breaks down
    inside your area, but aren’t from your area, you’ve the
    opportunity to beat out your competition for auto repairs on their vehicle, which
    can bring in several thousand dollars a year alone.

  24. Sammy January 30, 2013 at 8:26 pm #

    Thank you a lot… Rally good Article…

  25. Subhabrat February 2, 2013 at 2:04 am #

    Beautiful Tutorial!
    Many thanks :)

  26. Brigitte March 2, 2013 at 11:52 am #

    I like this blog so significantly, saved to my bookmarks .

  27. Ferdinand Lefeps March 3, 2013 at 6:12 pm #

    I’m trying to parse with mustache a json wich have this propertie

    custom_fields: {
    price: ["550"],
    sale_type: ["rent"]
    }

    Like this…but no way

    {{#custom_fields.sale_type}}{{.}}{{/custom_fields.sale_type}}

    Help would be very appreciated!

  28. Optio laboris consequuntur doloribus est March 15, 2013 at 5:02 pm #

    Harum dolor pariatur. Et alias beatae iusto qui necessitatibus occaecat exercitationem nulla dicta.

  29. Daniel April 10, 2013 at 10:26 pm #

    Great! Thank you!

  30. Brett Mitchell April 20, 2013 at 9:18 pm #

    Great article Chris. Thanks for the simplified and wide range of examples that you provide.

  31. car donation June 24, 2013 at 5:23 pm #

    I absolutely love your website.. Great colors & theme.
    Did you build this web site yourself? Please reply back as I’m wanting to create my very own site and would love to learn where you got this from or just what the theme is named. Cheers!

  32. sample phone scripts for fundraising July 4, 2013 at 8:27 pm #

    Hey There. I found your blog using msn. This
    is an extremely well written article. I’ll be sure to bookmark it and come back to read more of your useful info. Thanks for the post. I will definitely return.

  33. Manish July 28, 2013 at 11:28 am #

    Thanks for explaining while keeping all major scenario in mind.

  34. phone scripts for real estate investors July 30, 2013 at 1:29 am #

    My coder is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using WordPress on a number
    of websites for about a year and am concerned about switching to another platform.
    I have heard good things about blogengine.net.
    Is there a way I can transfer all my wordpress posts
    into it? Any kind of help would be greatly appreciated!

  35. Good August 23, 2013 at 12:14 am #

    Good example ! Excellent

  36. how do i look up cell phone numbers October 9, 2013 at 4:20 pm #

    Here are some of the benefits to having a cell phone. These days,
    there are various brands of phones, models and also more cell phone accessories you
    can buy. Article Source: you are looking for Reachout
    Wireless, click on the link.

  37. deny October 24, 2013 at 1:55 pm #

    thank you chris your article can help me, chris i want ask question how to make mustache and jquery seo friendly?, can you explain to me, thank you chris

  38. Urevich Sergei October 24, 2013 at 3:29 pm #

    Really good article, but did not find any information about escaping here :(, lost a lot of time.

    Just wanted to tell guys following:

    All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: {{{name}}}. You can also use & to unescape a variable.

    • Bryan January 16, 2014 at 2:15 pm #

      Yes, this is useful information, which should be included above. Thank you.

  39. Hieu October 26, 2013 at 5:48 am #

    Thanks for your tutorial! :)

  40. fdg January 29, 2014 at 4:33 am #

    dfgdfdsfsd

  41. camtoweb February 5, 2014 at 3:49 am #

    Thank you a lot!
    Rally good Article

  42. axel007 February 25, 2014 at 3:29 am #

    Good examples !
    But, you should look at the Knock-out Js library which propose a Template functionality which seems to be more readable for more complex cases.
    MVVM is made for that ;)

Trackbacks/Pingbacks

  1. Javascript Resources[updated] « Kooljoy.com Blog - December 29, 2011

    [...] HTML Templates with Mustache.js [...]

  2. Howto create Partials – Mustache.js – Marco Senkpiel - May 10, 2012

    [...] um die Notation zu finden wenn man das ohne ICanHaz.js etc. machen möchte. Deshalb mal hier ein Codesnippet aus dem Blog von Christophe [...]

  3. What is the difference between Mustache.render() and Mustache.to_html()? - June 3, 2012

    [...] documentation makes no mention of Mustache.to_html(), but every tutorial for Mustache.js online uses Mustache.to_html(). Therefore I am surely missing some [...]

  4. Tutorial: HTML Templates with Mustache.js | TechnoVeille - September 3, 2012

    [...] original : ici ‹ Wysihtml5 Tagués avec : Framework, Html, Javascript Publié dans [...]

  5. CouchDB Journal – Part 1 Establishing a Dev Environment » JetPgmr - October 5, 2012

    [...] Tutorial: HTML Templates with Mustache.js [...]

  6. หัดใช้ Mustache กันดีกว่า | KHASATHAN.IN.TH - October 30, 2012

    [...] Tutorial: HTML Templates with Mustache.js [...]

  7. JSON rendering : The Webtech Blog - December 12, 2012

    [...] is also MoustacheJS (where do they dream up these names?) – but from what I can see this seems to require JS [...]

  8. My Blog - March 3, 2013

    [...] tutorial by Christophe Coenraetes This entry was posted in Web and tagged mustache mustache.js on December [...]

  9. HTML Templates com Mustache.js | saviomd.com/blog - March 5, 2013

    [...] Link 5 de março de 2013 Tags: JavaScript [...]

  10. mustache tutorial | simple2013 - March 26, 2013

    [...] http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/ Share this:TwitterFacebookLike this:Like Loading… [...]

  11. Web Development | Annotary - April 24, 2013

    [...] More from Joseph Wolff: Recipes WordPress Murray JS Frameworks Sort Share coenraets.org       1 minute [...]

  12. js里怎么方便的输出大量的html - AJAX - 开发者问答 - May 15, 2013

    [...] 回复:https://github.com/janl/mustache.js +1,在最近的一个项目中使用了mustache,感觉很KISS,配合backbone使用效果更佳。http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/ 这边是个mustache.js的 tutorial,可能要翻墙。 [...]

  13. Web模板引擎——Mustache(转载) | Web开源笔记-专注Web开发技术,分享Web开发技术与资源 - December 27, 2013

    [...] 参考文章:http://coenraets.org/blog/2011/12/tutorial-html-templates-with-mustache-js/http://mustache.github.com/mustache.5.htmlhttp://ued.xinyou.com/2012/07/mustache_5_document.html [...]

Leave a Reply