2017-01-01 89 views
1

我在EJS循環,我想設置的CSS根據我的數據:EJS條件語句改變CSS

<% dummies.forEach(function(dummy) { %> 
    <div class="panel panel-???"> 
    </div> 
<% }) %> 

我的數據:

var dummies = [{ 
    type: "funny", 
    sure: "Yes" // this should generate panel-success 
}, { 
    type: "funny", // this should generate panel-a 
    sure: "No" 
}, { 
    type: "happy", // this should generate panel-b 
    sure: "No", 
}]; 

所以每當sure屬性是Yes,它產生panel-success。否則,它會根據type屬性生成css。

請幫忙。

回答

3

首先創建對象是這樣的:

<% 
let cssClass = { 
    funny: { 
     Yes: "success", 
     No: "a" 
    }, 
    happy: { 
     No: "b" 
    } 
} 
%> 

那麼你應該在模板只是輸出值:

<% dummies.forEach(function(dummy) { %> 
    <div class="panel panel-<%= cssClass[dummy.type][dummy.sure] %>"> 
    </div> 
<% }) %> 
+0

它的工作原理,謝謝!但是,這樣,我必須列出這兩個屬性的所有可能性(類型和確定)。其實每當「確定」是「是」,無論「類型」是什麼值,它總是面板成功,所以我想知道是否有可能使它更短... – shihandrana

+1

因此,如果確定===「是」面板型=「成功」 – Shazam

1

嘗試使用此代碼...

<% dummies.forEach(function(dummy) { %> 
    <div class="panel panel- 
     <% if (dummy.sure==="yes") { %> 
     success 
     <% else %> 
     <%= dummy.type %> 
     > 
    </div> 
    <% }) %> 

你可以將您的邏輯封裝在EJS運營商內部。它看起來有點凌亂,但它是什麼。根據服務器端設置的方式,您也可以從服務器端傳入參數,而不是在客戶端執行邏輯。

最好的方法將取決於到數據庫的訪問以及任何其他邏輯正在進行的繁重工作。