2011-12-18 29 views
31

我正在使用小胡子。我正在生成通知列表。通知JSON对象的样子:如何处理小胡子模板中的IF语句?

[{"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_type &行动if语句或case语句......

如果notified_type ==“友谊”渲染.. ....

如果notified_type ==“其他& &行动== “邀请” 渲染.....

是如何运作的?

+1

的可能的复制[如何做到的的if/else在mustache.js?](http://stackoverflow.com/questions/6027525/how-do-i-accomplish-an- if-else-in-mustache-js) – bjornte 2016-03-09 10:00:14

回答

43

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

无逻辑模板。

所以,一般的方法是做你的逻辑在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}} 

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

Handlebars提供必要的能力,让您可以有效地构建语义模板,而不会感到沮丧。

小胡子模板与把手兼容,所以你可以拿一个小胡子模板,将它导入到把手中,并开始利用额外的把手功能。

27

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

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

我们的目标是尽可能多的逻辑地搬出模板(这是有道理的)。

7

我有一个简单而通用的hack来执行键/值if语句,而不是布尔在胡须中(并以一种非常可读的方式!):

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

有了这个技巧,对象是这样的:

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

这使得胡子数据膨胀,但它是一个可用的和r值得考虑的可靠方法 – SketchBookGames 2016-01-27 22:22:08

+1

平等示例非常有用! – JeanValjean 2016-03-02 22:28:13

37

刚刚拿了一个过目胡子文档和他们支持“倒段”中,他们陈述

如果该键不存在,他们(反向的段)将被渲染,是假的,或者是一个空列表

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

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

展示如何如果真实,做假也很棒! – Triforcey 2016-06-09 18:21:14