我正在尝试使用(在我的把手中)我在 app.js 中全局设置的登录用户数据。
以下是我的代码:
app.js
// Set global variable
app.use(function (req, res, next) {
res.locals.user = req.user || null
next()
})
index.hbs
index.hbs 将呈现用户的帖子,对于每个帖子,它 将 post_title 呈现为 {{title}} ,将正文呈现为 {{body}}。这些都是 一切正常,但我想要的是帖子上方的编辑图标 只有登录的用户。所以如果总共有六个帖子 页面,其中只有两个是由登录用户更新的 图标必须显示在这两个帖子上方,其余帖子应该 显示时没有更新图标。所以在这里,updateIcon 函数 将与user(这是针对 post), ../user (这是上一级的登录用户,在 全局级别)和_id这是帖子ID。
<h1>Stories</h1>
<div class="row">
{{#each posts}}
<div class="col s12 m4">
<div class="card">
<div class="card-image">
{{{updateIcon user ../user _id}}}
</div>
<div class="card-content center-align">
<h5>{{title}}</h5>
<p>{{body)}}</p>
<br>
<div class="chip">
<img src="{{user.image}}" alt="">
<a href="/stories/user/{{user._id}}">{{user.displayName}}</a>
</div>
</div>
<div class="card-action center-align">
<a href="/stories/{{_id}}" class="btn grey">Read More</a>
</div>
</div>
</div>
{{else}}
<p>No stories</p>
{{/each}}
</div>
hbs.js
这是我编写 updateIcon 的 javascript 文件 功能。它从 handlebars 模板接收参数 函数调用,以及一个附加参数 floating 设置为
.true
updateIcon: function (postUser, loggedInUser, postId, floating = true) {
console.log(`${postUser._id} ${loggedInUser._id}`)
if (postUser._id.toString() === loggedInUser._id.toString()) {
if (floating) {
return `<a href="/stories/edit/${postId}" class="btn-floating halfway-fab blue"><i class="fas fa-edit fa-small"></i></a>`
} else {
return `<a href="/stories/edit/${postId}"><i class="fas fa-edit"></i></a>`
}
} else {
return ''
}
},
当我运行我的应用程序并单击以检查菜单中的所有帖子时,我 得到以下错误:
TypeError: Cannot read properties of undefined (reading '_id') at Object.updateIcon (/media/jdpc/HDD1/myPortfolioProjects/pick-a-pen/helpers/hbs.js:25:50)