Wednesday, May 13, 2015

Javascript Templating using Mustache

Sometimes we need to generate rows of html from ajax response. Those who come from JSP or other server side template engines understand that how convenient it becomes to use a templating engine. Mustache serves the same need on Javascript side. Mustache can be used as a templating engine for many other languages as mentioned in their website at https://mustache.github.io/ . A basic tutorial of Mustache can be seen at https://github.com/janl/mustache.js

I would not go through the tutorial of mustache as that can be seen at above links. I would try to outline where Mustache can be useful and where it's not so.


Mustache is quite useful where the template is fixed in nature. Let's say you want to create a table dynamically where each row displays details of each student in a class. Also for each student we have a fixed fields to show. For example for each student we want to show

Name:
DOB:
Class:

A typical Mustache template would look like

Name: {{name}}
DOB: {{dob}}
Class: {{class}}

Let's say now we want to display the information more dynamically. For each student we also want to show the subjects and their marks. However students have varied number of subjects. In that case, Mustache would not be of much help as one has to process logic to figure out which subjects to show. Also another use case be if for example say not every students dob is not available. (Take it for example sake :)). One wants to show DOB only if it is available and not to show the row itself if DOB is not there.

That's the reason also why Mustache is called as Logic less template. It's a great framework but choose it based on your use case.

No comments:

Post a Comment