繁体   English   中英

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

[英]How to handle an IF STATEMENT in a Mustache template?

我正在使用小胡子。 我正在生成通知列表。 通知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做一个if语句或case语句......

如果notified_type == "Friendship"呈现......

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

这是如何运作的?

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

无逻辑模板。

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

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

然后在你的模板中:

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

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

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

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

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

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

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

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

一般情况下,使用#语法:

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

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

我有一个简单而通用的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;
}

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

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"
};

在转型之前会是这样的:

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

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

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

{{#notified_type=invite}}
    invite…
{{/notified_type=invite}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM