AnApprentice AnApprentice - 1 year ago 127
jQuery Question

How to handle an IF STATEMENT in a Mustache template?

I'm using mustache. I'm generating a list of notifications. A notification JSON object looks like:

[{"id":1364,"read":true,"author_id":30,"author_name":"Mr A","author_photo":"image.jpg","story":"wants to connect","notified_type":"Friendship","action":"create"}]

With mustache, how can I do a if statement or case statement based on the notified_type & action...

If notified_type == "Friendship" render ......

If notified_type == "Other && action == "invite" render.....

How does that work?


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:


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.