[英]Why can't I pass functions from Express.js to EJS like I pass other variables?
我正在使用Express 、 EJS和 MongoDB 開發博客應用程序(單擊鏈接以查看GitHub 存儲庫)。
嘗試對帖子進行分頁時,我遇到了將newerPosts
和olderPosts
傳遞給視圖的問題。 我像posts
變量(和其他變量)一樣傳遞它們:
exports.getPosts = async (req, res, next) => {
//pagination params
var perPage = 10;
var currPage = req.body.page ? parseInt(req.body.page) : 1;
const newerPosts = function() {
currPage = currPage + 1;
console.log(currPage);
}
const olderPosts = function() {
currPage = currPage - 1;
console.log(currPage);
}
const posts = await Post.find({}, (err, posts) => {
if (err) {
console.log('Error: ', err);
} else {
res.render('default/index', {
moment: moment,
layout: 'default/layout',
website_name: 'MEAN Blog',
page_heading: 'XPress News',
page_subheading: 'A MEAN Stack Blogging Application',
posts: posts,
newerPosts: newerPosts,
olderPosts: olderPosts
});
}
})
.sort({
created_at: -1
})
.skip((currPage - 1) * perPage)
.limit(perPage)
.populate('category');
};
在視圖中:
<div class="px-1">
<a class="btn btn-primary" href="#" onclick=<%="olderPosts()"%>>← Older Posts</a>
</div>
<div class="px-1">
<a class="btn btn-primary" href="#" onclick=<%="newerPosts()"%>>Newer Posts →</a>
</div>
然而,我得到了Uncaught ReferenceError: newerPosts is not defined
來自瀏覽器的錯誤消息。
我究竟做錯了什么? 最接近的工作選擇是什么?
您可以執行以下操作:創建一個名為functions.ejs
的新 ejs 文件:
<script>
function test(){console.log(1)}
</script>
然后使用<%- include('functions'); %>
<%- include('functions'); %>
在您正在渲染的模板內。 在開始時使用它,以便在調用它時定義 function。
在相應的路由中,使用:
res.render('default/index', {
...,
name: 'test'
});
在您的模板中可以執行以下操作:
<button onclick="<%=name%>()"> <%= btnText %> </button>
但是,當我查看您要通過的 function 時,我看到您想使用currPage = currPage + 1;
. 這不會起作用,因為一旦頁面被渲染, currPage
中的 currPage 就不再引用了,因為那時一切都是 static html。
如果要更改頁面等,則需要實現一些前端邏輯。
檢查這個:
const posts = await Post.find({}, (err, posts) => {
xxxx ... res.render()
})
我認為這里你需要對 Promise 用法的邏輯進行一些更改......想想 - 如果出現錯誤會發生什么? 你在哪里處理? 更有趣的是 - 在 promise 返回結果之后 - 你從 function 退出的位置? ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.