How to handle an IF STATEMENT in a Mustache template? How to handle an IF STATEMENT in a Mustache template? javascript javascript

How to handle an IF STATEMENT in a Mustache template?


Just took a look over the mustache docs and they support "inverted sections" in which they state

they (inverted sections) will be rendered if the key doesn't exist, is false, or is an empty list

http://mustache.github.io/mustache.5.html#Inverted-Sections

{{#value}}  value is true{{/value}}{{^value}}  value is false{{/value}}


Mustache templates are, by design, very simple; the homepage even says:

Logic-less templates.

So the general approach is to do your logic in JavaScript and set a bunch of flags:

if(notified_type == "Friendship")    data.type_friendship = true;else if(notified_type == "Other" && action == "invite")    data.type_other_invite = true;//...

and then in your template:

{{#type_friendship}}    friendship...{{/type_friendship}}{{#type_other_invite}}    invite...{{/type_other_invite}}

If you want some more advanced functionality but want to maintain most of Mustache's simplicity, you could look at Handlebars:

Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.

Mustache templates are compatible with Handlebars, so you can take a Mustache template, import it into Handlebars, and start taking advantage of the extra Handlebars features.


In general, you use the # syntax:

{{#a_boolean}}  I only show up if the boolean was true.{{/a_boolean}}

The goal is to move as much logic as possible out of the template (which makes sense).