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) {
		'<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);


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);


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);

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>


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);


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>" +
var html = Mustache.to_html(template, data);


  • 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);


Christophe Coenraets


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);


John Smith


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);


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);


  • 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);


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>" +
var partials = {employee: "<li>{{firstName}} {{lastName}}</li>"};
var html = Mustache.to_html(tpl, data, partials);



  • Christophe Coenraets
  • John Smith


  • Paula Taylor
  • Lisa Jones


You can run all the examples here.


  • Pingback: Javascript Resources[updated] « Kooljoy.com Blog()

  • Chris

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

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

  • Larry

    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:

    • Larry

      That didn’t show up very good I want to see the output like this:

  • Victor

    Nice work! Help me a lot! thanks

  • Jan

    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.

  • 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.

  • Chintan

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

  • alex

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



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


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

  • Joe

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

  • Pingback: Howto create Partials – Mustache.js – Marco Senkpiel()

  • Yasin Coşkun

    nice tutorial thanx

  • Pingback: What is the difference between Mustache.render() and Mustache.to_html()?()

  • Landon

    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.

  • Thanks, good post

  • raj

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


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

    any help will be appreciated

  • Nitesh

    You explained all cases… really helped

  • mauro

    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

      $.get(url, function(data) {
      var template = data;
      var html = Mustache.to_html(template, person);

  • Pingback: Tutorial: HTML Templates with Mustache.js | TechnoVeille()

  • Kumaresan

    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”,
    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?


    • Kumaresan

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

      • narun


  • Manikandan Ganesan

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

  • Pingback: CouchDB Journal – Part 1 Establishing a Dev Environment » JetPgmr()

  • Partha Das

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

  • Pingback: หัดใช้ Mustache กันดีกว่า | KHASATHAN.IN.TH()

  • Tejas Nityanand

    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

      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.

  • Bas Velthuizen


    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?


  • Pingback: JSON rendering : The Webtech Blog()

  • Minerva

    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.

  • 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.

  • Sammy

    Thank you a lot… Rally good Article…

  • Subhabrat

    Beautiful Tutorial!
    Many thanks :)

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

  • Pingback: My Blog()

  • Ferdinand Lefeps

    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


    Help would be very appreciated!

  • Pingback: HTML Templates com Mustache.js | saviomd.com/blog()

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

  • Pingback: mustache tutorial | simple2013()

  • Daniel

    Great! Thank you!

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

  • Pingback: Web Development | Annotary()

  • Pingback: js里怎么方便的输出大量的html - AJAX - 开发者问答()

  • 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!

  • 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.

  • Manish

    Thanks for explaining while keeping all major scenario in mind.

  • 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!

  • Good

    Good example ! Excellent

  • 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.

  • deny

    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

  • Urevich Sergei

    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

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

  • Hieu

    Thanks for your tutorial! :)

  • Pingback: Web模板引擎——Mustache(转载) | Web开源笔记-专注Web开发技术,分享Web开发技术与资源()

  • fdg


  • Thank you a lot!
    Rally good Article

  • axel007

    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 ;)

  • s

    continuously i used to read smaller posts that as well clear
    their motive, and that is also happening with this article which I am
    reading now.

  • “Buy Gold Safely” not only goes into depth about the different types of gold
    and silver investment, but also where to purchase it, store
    it, how to invest using your IRA or 401K and much much more.

    Conventional wisdom on gold IRAs has actually evolved as the uses of gold have actually evolved.

    The website is putting in a lot of efforts to find the importance
    of trading different commodities that can be profitable for the
    customers relying on the platform.

  • We’re a group of volunteers and starting a new scheme
    in our community. Your web site offered us with helpful helpful and work on
    . You have a formidable process and our whole neighborhood will likely be thankful to you .

    Definitely imagine that you said . Your favorite justification seemed to be on the web easy thing to keep in mind of .
    I tell you , i definitely get annoyed think issues
    clear that not realize about . You controlled well
    as defined everything managed to hit the nail on the top
    without having side-effects , others cAN could take a signal.
    Will probably be again to get more. Thank you

  • C’est un véritable plaisir de lire ce blog

  • I needed to thank you for this good read!! I certainly loved every
    bit of it. I have got you book marked to look at new things you post…

  • How use mustcache to pagination ?

    Eg: I have all_pages = 10; how can i render the pagination html ?

  • Jе publie un petit commenhtaire dans le but de congratuler le webmaster

  • Hey there! I know this is kind of off-topic
    however I needed to ask. Does managing a well-established website
    like yours require a large amount of work? I’m completely new to writing a blog however I do write in my journal everyday.
    I’d like to start a blog so I will be able to share my
    own experience and thoughts online. Please let me know if you have any kind of recommendations or
    tips for new aspiring bloggers. Thankyou!

  • I think that what you posted mwde a great deal of sense.
    But, what about this? what if you added a little information?
    I ain’t saying yyour content iss nott solid, but supose you added a title that makes pekple want more?I mean Tutorial: HTML Templates with Mustache.js | Christophe
    Coenraets is a little boring. You could look
    at Yahoo’s home ppage and watch how they create news headlines to grab viewers to open the
    links. You migt add a vdeo or a related piic or two
    to get readers excited abput what you’ve got to say.
    Juust my opinion, it would make your website a little livelier.

  • Hello, for all time i used to check weblog posts here in the early
    hours in the daylight, since i enjoy to find out more and more.

  • It’s remarkable designed for me to have a website, which is helpful in favor of my experience.
    thanks admin

  • Gay

    Undeniably believe that which you stated. Your favorite reason seemed
    to be on the internet the simplest thing to be aware of.
    I say to you, I definitely get annoyed while people think
    about worries that they plainly don’t know about.
    You managed to hit the nail upon the top and defined out the whole thing without having side-effects
    , people could take a signal. Will likely be back to get more.

  • You could certainly see your expertise in the work you write.
    The world hopes for even more passionate writers
    such as you who aren’t afraid to say how they believe.
    All the time follow your heart.

  • It’s awesome to pay a quick visit this website and reading
    the views of all friends on the topic of this post, while I am
    also zealous of getting experience.

  • I am extremely impressed with your writing talents
    and also with the structure for your weblog. Is that this a paid topic or did you customize it your self?
    Anyway stay up the nice quality writing, it’s uncommon to look a great
    weblog like this one today..

  • This is a topic that is close to my heart…
    Take care! Where are your contact details

  • Pingback: Creating HTML Templates with Mustache.js | Way 2 Webdev()

  • Pingback: pengembang pajanlom | Mustache()

  • efkan

    Your examples (PhoneGap, Mongo etc.) and tutorials are really perfect and very understandable.

    Thank you for your wonderful works. I follow you :)

  • Peter Pan

    Why do you load googleanalytics this way on your website?

    (function() {
    var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
    ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
    var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);

    NoScript was not able to detect this.

  • Pingback: Object JavaScript – Introduction to Templates in MVVM Using Knockout.js, Mustache | DevDays®()

  • I have a HUGE problem with this and I can’t find help for it anywhere.

    Externalizing the template does not work because when I try to access the innerHTML, text or any other property of the Script element, everything inside of curly braces disappears!

    So if my template is like so:


    When I try to access that template, I use jQuery (But please understand the exact same results happen with god ol’ document.getElementById)

    var template = $(“#templateTest”).html();

    And the contents of the template variable are the following:


    So what on earth is going on here? I’m using the methods you’re describing and the code just flat-out does not work.

    The only big difference I can see is that my templates are not hard-coded onto the main page. They are nested inside of a DIV tag which I’m rendering to the page with jQuery so that part is read externally. The disappearance of the curly braces might be happening when jQuery renders the script tag onto the page itself.

    I’m desperate. First my solution was to replace “{{” and “}}” with “[[” and “]]” and just replace them back before I render with a regular expression, which worked perfectly fine. Now suddenly that does not work anymore, almost overnight it seems. I’ve had to resort to using double parentheses which is utterly ridiculous.

    Either jQuery or HTML is destroying anything I put in Curly (and now Square) braces and it’s driving me nuts and making my job impossible.

    • In case you were wondering this website wasn’t designed with enough forethought to consider that people might post innocuous examples of code.

      The point I was trying to make was that anything inside of curly braces, including the braces themselves, disappears when I try to access the innerHTML of the script element.

  • Pingback: How to render a mustache template using bootstrap jquery plugin | 我爱源码网()

  • Pingback: Tutorial: HTML Templates with Mustache.js | Christophe Coenraets | Andreas Plahn Developer Blog()

  • WOW! Nice work! Help me a lot! thanks

  • these examples it’s great!!

  • Wonderful article…

    Helped me a lot while working with HTML Templates. Good narration style.

    Thanks a lot again.

  • Pingback: (3/10) Setting Up Mustache.js – Graphing Data with HTML5 Animation | Code Cascade()

  • Pingback: (7/10) Templating to a Table – Graphing Data with HTML5 Animation | Code Cascade()

  • Remember to refer to sample 3 for a traditional setup

  • Pingback: Dilettante attempt @MustacheJS with ASP.NET | My cUr10U5 w0rlD 1N 8i75 @ND 8yt3$()

  • usefull for newbies

  • Great post! Thanks for you insight and sharing it with us! I like this blog and I will be here again.

  • Utilizing this type of story driving the application, there isn’t delight the product brings guiding the nation’s things a few of the most effective watches globally.

  • Thanks a lot for this nice article

  • Chanu

    this very good tutorial. very clear explanation and examples.Thank You.

  • Awesome!!


  • Pingback: Build to performe – mustache.js | digitalwhores()

  • Muy buen tutorial


  • This tutorial and the downloaded application

  • nice work i like your shareds bro

  • Sameer

    its very bad..not working fine ………not good ….

  • harika çalışmalar var başarılı helal olsun

  • Formalarımızda kullandığımız kumaş; birinci sınıf mikro-interlok olup; esnek-fit, anti-bakteriyel, termo-balans ve hemen kuruma özelliğine sahiptir. Futbol maçlarınızda size hareket özgürlüğü sunan bu formalar; günlük olarak giyilebilecek kadar şık tasarlanmıştır. Forma Modellerimiz özel dikim ve Dijital baskılı olarak iki tür üretilmektedir.
    Firmamızın en fazla üretim yaptığı, spor çoraplarında kullandığımız ürünler: pamuk ,koton, polyester, naylon ve likradır. Anti-bakteriyel içermektedir.

  • качество, надежность, экономичность и связанные работы выполняются imalattan.profesyonel команду

  • Pingback: Mustache JS na przykładzie aplikacji Express. Część 2/2. - javascript-html5-tutorial.pl | javascript-html5-tutorial.pl()

  • Pingback: Mustache JS tutorial by jQuery and Express application example. Part 2/2. - javascript-html5-tutorial.com()

  • Harika bir Firma rehber sitesi ve tamamen ücretsiz…

  • You know, I’ve been here probably about 100 times as a reference. I just wanted to say, Thank you very much for taking the time to write up this article on Mustache. It’s been invaluable to me.

    Thank you, Thank you, Thank you!

  • This tutorial and the downloaded v-wooow yeaa

  • Achim

    Wow ! Took me about 10 minutes to include mustache and it worked immediately !
    Thank you. This saved me hours of work tonight…