Mustache.js LogoMustache.js provides a simple, yet powerful way to populate one piece of HTML many times with a data set. In this article, we’ll learn how to specify markup that will be rendered when there is an absence of data.

In an earlier post: “Mustache.js – The Absolute Basics“, we learned how easy it is to leverage Mustache.js for simple, yet powerful client-side templating. In that article, we saw that you can use your template to check and see if a data point has a value, and if so, render some markup.

But what if a “row” of data is missing one or more of its parts? In that case, we might want to render some specific markup that says “no data found”. When using Mustache.js, this is accomplished by using the following set of characters: {{^foo}}no data!{{/foo}}, where “foo” is our data point. Then, when Mustache.js sees that “foo” does not exist, or has a “falsy” value, it will render whatever HTML we put inside of the two specified tags. In this case, it would be the text: “no value!”.

In this way, we can create an “if not” logic, in which we are saying: “if there is no foo, or if foo is ‘falsy’, then render ‘no value!’.

Example # 1

In Example # 1, we have the data object that will be used in our template. Make note that not every user in the array has the same amount of data. Some people are missing either “region”, “phone” or “email”. This is important because we will introduce logic into our template that acts upon the absence of data.

Example # 2

In Example # 2, we have the HTML template that we will use with Mustache.js. You’ll notice that other than “name”, every data point is represented twice. First, there is an “if” condition, which is wrapped with these two tags: {{#foo}}Foo: {{foo}}{{/foo}}. What is being expressed here is: “if there is a value for the “foo” dataPoint, then show it. Then there is an “if not” condition wrapped with these two tags: {{^foo}}No Foo!{{/foo}}. In this case, Mustache.js is being told: If there is no value for “foo”, show this HTML.

Example # 3

In Example # 3, we have code that is virtually identical to that which we used in the Mustache.js basics article. First, we get a reference to our template: div#template, and then we use the Mustache.render method to fill the “output” variable with markup that has been populated with our data. Finally, we simply append this markup to the element with the “.box” class.

Here is a JS Fiddle link for our completed working example: http://jsfiddle.net/pg886/