2011-12-18 74 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