Mustache JS is an open source logic-less template system developed for languages such as JavaScript, C#.NET, Java or any web programming languages. Mustache provides templates and views as the basis for creating dynamic templates. It is easy to be designed in such a way to separate the logic between UI and JavaScript.
Most of the web developers that are not aware of template systems create new chunks of HTML code and dynamically insert them into the DOM using JavaScript. A common way of doing this is use innerHTML for conventional JavaScript approach, or using JQuery .html(content) to replace the value of your DOM.
The old technique no longer works for developers nowadays, because it makes developers difficult to maintain the system improvement because of the DOM id or classes existed inside your JavaScript source code or certain IF ELSE logic appeared in the HTML content.
Not just it affect code readability, without separately the business logic from the HTML templates, it makes life much more difficult in term of reusing the template for other purposes. Below are a few easy examples on how to use Mustache JS.
Mustache Source Code
var rendered = Mustache.render($("#template"), {name: "Khai"}); $('#target').html(rendered);
Template Source Code
<script id="template" type="text/script"> Hello {{ name }}! </script>
Result / Output
Hello Khai!
And you can complete your repeater like below,
Data Source Code
{ "person": [ { "name": "Khai" }, { "name": "Yong" }, { "name": "Lim" } ] }
Template Source Code
{{#person}} <b>{{name}}</b> {{/person}}
Besides that, you can include simple IF ELSE condition in your Mustache JS like below, # represent true, ^ represent inverted.
Template Source Code
{{#value}} Value is True {{/value}} {{^value}} Value is False {{/
value
}}
For more examples or technique you can refer to https://github.com/janl/mustache.js or http://www.stackoverflow.com
Conclusion
Overall Mustache JS is very easy to be implemented. And you only required to include a single Mustache JS file. But if you are developing a more comprehensive table / repeater that required things like template, sorting, instant edit mode, or search as a whole package, probably Knockout JS will be a better solution.
You must be logged in to post a comment.