如何在索引頁面上使用EJS在Express中循環顯示多個模型的數據

[英]How to loop through and display data from multiple models in express using EJS on the index page


I have 2 models (Revive and Launch). I would like to loop through both and display the data on one view (index.ejs)

我有2個型號(Revive和Launch)。我想循環遍歷兩個並在一個視圖上顯示數據(index.ejs)

Here is the router for Index:

這是索引的路由器:

var express = require('express');
var router = express.Router();

var Revive = require('../models/revive');
var Launch = require('../models/launch');

/* GET home page. */
router.get('/', function(req, res, next) {
  Revive.find({}, function (err, revives) {
    if(err) {
      console.log(err)
    } else {
      res.render('pages/index', {revives: revives});
    }
  });
  Launch.find({}, function (err, launches) {
    if(err) {
      console.log(err)
    } else {
      res.render('pages/index', {launches: launches});
    }
  });
});

And here is the view (index.ejs):

這是視圖(index.ejs):

<% revives.forEach(function(revive) { %>

    <div class="copy">
        <p class="secondary">8.7/10 • Animation, Comedy</p>
        <h3 class="ellipsis"><h4><%= revive.reviveShowName %></h4></h3>
    </div>

<% }); %>

<% launches.forEach(function(launch) { %>

    <div class="copy">
        <p class="secondary">8.7/10 • Animation, Comedy</p>
        <h3 class="ellipsis"><h4><%= launch.launchShowName %></h4></h3>
    </div>

<% }); %>

While I'm able to loop through only one and display successfully as soon as I add the second loop it throws a header error 'launches is not defined...'

雖然我只能循環通過一個並且在我添加第二個循環后成功顯示它會拋出標題錯誤'啟動未定義...'

1 个解决方案

#1


0  

Quick and dirty solution for all who run into the same issue:

對於遇到同樣問題的所有人來說,快速而又臟的解決方案:

router.get('/', function(req, res, next) {
  Revive.find({}, function (err, revives) {
    if(err) {
      console.log(err)
    } else {
      Launch.find({}, function (err, launches) {
        if(err) {
          console.log(err)
        } else {
          res.render('pages/index', {revives: revives, launches: launches});
        }
      });
    }
  });
});

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/11/21/72fb0ee99e83a1e7fd51cc11c2b752ee.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com