如何处理Mustache模板中的IF STATEMENT?

AnA*_*ice 50 javascript templates mustache

我正在使用小胡子.我正在生成通知列表.通知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"}]
Run Code Online (Sandbox Code Playgroud)

有胡子,我怎么能根据notified_type&action... 做一个if语句或case语句

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

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

这是如何运作的?

mu *_*ort 63

小胡子模板在设计上非常简单; 该网页甚至说:

无逻辑模板.

所以一般的方法是在JavaScript中使用你的逻辑并设置一堆标志:

if(notified_type == "Friendship")
    data.type_friendship = true;
else if(notified_type == "Other" && action == "invite")
    data.type_other_invite = true;
//...
Run Code Online (Sandbox Code Playgroud)

然后在你的模板中:

{{#type_friendship}}
    friendship...
{{/type_friendship}}
{{#type_other_invite}}
    invite...
{{/type_other_invite}}
Run Code Online (Sandbox Code Playgroud)

如果你想要一些更高级的功能,但想要保持Mustache的大部分简洁性,你可以看看Handlebars:

Handlebars提供了必要的功能,让您可以有效地构建语义模板而不会受挫.

Mustache模板与Handlebars兼容,因此您可以使用Mustache模板,将其导入Handlebars,并开始利用额外的Handlebars功能.


Luc*_*cas 56

只是看看胡子文档,他们支持他们陈述的"倒置部分"

如果密钥不存在,为假,或者为空列表,则将呈现它们(倒置的部分)

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

{{#value}}
  value is true
{{/value}}
{{^value}}
  value is false
{{/value}}
Run Code Online (Sandbox Code Playgroud)

  • 很好的展示如何如果真的,也做错了! (4认同)
  • 这个答案实际上对我来说比接受的答案更好,因为我想在使用 Mustache 的“jira 自动化”插件中使用它。 (3认同)
  • 这就是答案,伙计们 (2认同)
  • 澄清一下,除了如上所示的真或假检查之外,我们不能在条件中添加任何其他内容。 (2认同)

Dav*_*ton 32

通常,您使用以下#语法:

{{#a_boolean}}
  I only show up if the boolean was true.
{{/a_boolean}}
Run Code Online (Sandbox Code Playgroud)

目标是尽可能多地从模板中移出逻辑(这是有道理的).


小智 12

我有一个简单而通用的hack来执行key/value if语句而不是boolean-only in mustache(并且以极易读的方式!):

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;
}
Run Code Online (Sandbox Code Playgroud)

有了这个hack,就像这样一个对象:

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"
};
Run Code Online (Sandbox Code Playgroud)

在转型之前会是这样的:

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
};
Run Code Online (Sandbox Code Playgroud)

你的小胡子模板看起来像这样:

{{#notified_type=friendship}}
    friendship…
{{/notified_type=friendship}}

{{#notified_type=invite}}
    invite…
{{/notified_type=invite}}
Run Code Online (Sandbox Code Playgroud)