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?
This question is related to
javascript
templates
mustache
I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :
function buildOptions (object) {
var validTypes = ['string', 'number', 'boolean'];
var value;
var key;
for (key in object) {
value = object[key];
if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
object[key + '=' + value] = true;
}
}
return object;
}
With this hack, an object like this:
var contact = {
"id": 1364,
"author_name": "Mr Nobody",
"notified_type": "friendship",
"action": "create"
};
Will look like this before transformation:
var contact = {
"id": 1364,
"id=1364": true,
"author_name": "Mr Nobody",
"author_name=Mr Nobody": true,
"notified_type": "friendship",
"notified_type=friendship": true,
"action": "create",
"action=create": true
};
And your mustache template will look like this:
{{#notified_type=friendship}}
friendship…
{{/notified_type=friendship}}
{{#notified_type=invite}}
invite…
{{/notified_type=invite}}
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).
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}}
Source: Stackoverflow.com