EJS条件IF

时间:2017-01-06 15:15:04

标签: ejs

新手到EJS,

尝试从MongoDB获取数据并在视图中显示。如果没有数据,显示“otherCondition”,如果有数据,请循环并显示“repeat”和“unrelated”

 <% 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>没有显示。

提前致谢。

1 个答案:

答案 0 :(得分:0)

此处eventData始终是一个数组,因为在服务器端,您使用的查询是 find()方法, 所以 typeof eventData将始终返回一个对象,因此您的第一个条件始终为true,因此控制器永远不会转到otherCondition。

如果条件

,最好先检查eventData的lenth

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

相关问题