2017-01-06 44 views
0

新手到EJS這裏,EJS有條件IF

試圖從MongoDB獲取數據並在視圖中顯示。如果沒有數據,顯示「otherCondition」,如果有數據,做循環,並顯示「重複」和「無關」

<% if (typeof eventData == 'object'){ %> // check if its empty/undefined 
    <% eventData.forEach(function(event) { %> // loop if exists 
     <div class="repeat"> 
      ...       // other code 
     </div> 
    <% }) %>        // end of loop 
    <div class="unrelated">     
      ...       // other code (again) 
    </div> 
<% } else { %>       // else condition 
    <div class="otherCondition">     
      ...       // other code (again) 
    </div> 
<% } %> 
上述

EJS代碼,以下航線代碼:

router.route('/').get(function(req, res, next) { 
     mongoose.model('Event').find({}, function(err, events) { 
      if (err) { 
       return console.error(err); 
      } else { 
       res.format({ 
        html: function() { 
         res.render('events', { 
          eventData: events, 
          user: req.user, 
         }); 
         if (typeof eventData == 'object') 
          console.log('display new events: ' + eventData); 
         else 
          console.log('no events, sorry :('); 
        } 
       }); 
      } 
     }); 
    }) 

可能另一個愚蠢的問題,但任何人都可以幫助我如何解決這個問題?在控制檯中,我得到no events, sorry :(,但我的<div class="otherCondition"></div>未顯示。

在此先感謝。

回答

0

這裏EVENTDATA始終是一個數組,因爲在服務器端你使用的查詢是find()方法方法, 所以的typeof EVENTDATA總是會返回一個對象因此你的第一個條件始終是真實的,因此控制器從未轉到otherCondition 。

更好您檢查EVENTDATA的lenth在第一if條件

<% if(constructor.eventData === Array && eventData.length > 0){ %> 
 
    <% eventData.forEach(function(event) { %> // loop if exists 
 
    <div class="repeat"> 
 
     ...       // other code 
 
    </div> 
 
    <% }) %>        // end of loop 
 
    <div class="unrelated">     
 
     ...       // other code (again) 
 
    </div> 
 
<% }else{ %> 
 
    <div class="otherCondition">     
 
     ...       // other code (again) 
 
    </div> 
 
<% } %>