簡體   English   中英

Node.js向EJS發送函數

[英]Nodejs send function to ejs

在app.js中:

    app.locals.count = function(id, call) {
var myId =  mongoose.Types.ObjectId(id)
db.collection('comment').aggregate({$match: {postid: myId}}, {$group : {_id: '$postid', nb: {$sum: 1}}}, 
function(err, cb){
for (i = 0; i < cb.length; i++) { var la = cb[i]; return call(la.nb);  };
});
}

在index.ejs中:

<% count(indexpost._id, function( result ){ %> <%= result %> <% }); %>

//不返回任何結果,但:

<% count(indexpost._id, function( result ){ %> <%= console.log(result) %> <% }); %>

在終端中返回結果。

如何在index.ejs中顯示結果? 謝謝

編輯#1 ##################################

app.locals.count = function(id, call){
var myId =  mongoose.Types.ObjectId(id)
var caca = ccount(myId);
call(caca);
}

function ccount(myId){
db.collection('comment').aggregate({$match: {postid: myId}}, {$group : {_id: '$postid', nb: {$sum: 1}}}, 
function(err, cb){
for (i = 0; i < cb.length; i++) {
  var la = cb[i];
  var value = la.nb;
  return la.nb;
};
});
}

在index.ejs中//返回未定義

但是:

app.locals.count = function(id, call){
var myId =  mongoose.Types.ObjectId(id)
var caca = 2;
call(caca);
}

在index.ejs中//返回2

ccount函數的方法返回錯誤。

只需在app.locals上注冊此功能,其余邏輯就不會改變。 現在您可以在ejs上調用該函數

在app.js中:

function count(id, call) {
var myId =  mongoose.Types.ObjectId(id)
db.collection('comment').aggregate({$match: {postid: myId}}, {$group : {_id: '$postid', nb: {$sum: 1}}}, 
function(err, cb){
for (i = 0; i < cb.length; i++) { var la = cb[i]; return call(la.nb);  };
});
}

app.locals.count =count ;

在index.ejs中

% count(indexpost._id, function( result ){ %> <%= result %> <% }); %>

如果您具有標題,文本等屬性,我想您可以做這樣的事情

  <% result.forEach(function(item) { %>
<ul>
    <li><%= item.title%></li>

    <li><%= item.text%></li>
</ul>
  <% }); %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM