So far mustache is great, but logic-less now does not seem to be a feature. Suppose, I have to render template in which I can have user’s email and name.
If both email and name are present I want my rendered result to be:
<a href="mailto:EMAIL">NAME</a>
If email is present, but not name, the result would be:
<a href="mailto:EMAIL">EMAIL</a>
If just name is present, template should be rendered to:
NAME
So now I have to do something like:
{{#email}}<a href="mailto:{{email}}">{{#name}}{{name}}{{/name}}{{^name}}{{email}}{{/name}}</a>{{/email}}{{^email}}{{name}}{{/email}}
This is SO UGLY! And this is just 3 conditions! What if I will need more? I feel like there should be another way of doing the same in mustache. Or shouldn’t it?
So, mustache developers think that being logic-less is a good thing, but I have an argument. Most of the times we need to check some variable in template (most of the times we just need to check only existence). So I would do something like:
{% if email %}{{ email }}{% else %}{{ name }}{% endif %}
and this looks much more comprehensive then
{{#email}}{{email}}{{/email}}{{^email}}{{name}}{{/email}}
isn’t it?
If I need to check name too:
{% if email %}{{email}}{% elif name %}{{name}}{% else %}Anonymous{% endif %}
vs
{{#email}}{{email}}{{/email}}{{^email}}{{#name}}{{name}}{{/name}}{{^name}}Anonymous{{/name}}{{/email}}
If no, would you suggest another templating library for rendering templates in javascript? Integration with jQuery (jQuery-plugin) is an advantage, but not a requirement – I can do it on my own.
Thanks.
There’s always Handlebars which is a little more feature rich than vanilla Mustache (it’s a superset of Mustache), and of course you can use any of the other countless templating engines available for JS. If you go with Handlebars you could even reimplement a version of the
{{#if}}block helper that accepts multiple arguments, like this (warning: very slightly tested, writing mostly out of the top of my head)and use it like this:
Be aware that this can be considered “cheating” by purists as you are implementing some kind of a compound logic operator, even more making it accept an indeterminate amount of params.
The point of Mustache is to have a very minimal spec that is easily ported across programming languages so that you can interchangeably reuse your templates in the back end and front end.