如何处理胡须模板中的 IF 语句?

我正在使用胡子。我正在生成一个通知列表。一个通知 JSON 对象看起来像:

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

有了胡子,我怎么能做一个如果语句或案例语句的基础上的 notified_typeaction..。

如果 notified_type == "Friendship"渲染... ..。

如果 notified_type == "Other && action == "invite"渲染... ..。

这是怎么回事?

141389 次浏览

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).

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.

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}}

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}}