这是我第一次用车把。 我正在尝试比较userid和登录的用户id。 我正在使用Mongoose在MongoDB中保存数据。 我从StackOverflow找到了一个帮助器,但它似乎没有比较价值。 下面是我正在使用的用户,跟踪器和代码的模式。
var trackerSchema = new mongoose.Schema({
description: {
type: String,
required: [true, 'Please add an description']
},
createdAt: {
type: Date,
default: Date.now
},
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
}
});
mongoose.model('Tracker', trackerSchema);
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
const User = mongoose.model('User', UserSchema);
app.js文件中的Helper函数
const hbs = exphb.create({
extname: 'hbs',
defaultLayout: 'mainLayout',
layoutDir: __dirname + 'views/layouts/',
partialsDir: __dirname + '/views/partials/',
helpers: {
ifEqual: function (v1, v2, options) {
if (v1 != v2) {
return options.inverse(this);
}
return options.fn(this);
},
}
})
在handlebar文件中使用helper函数ifEqual
{{#each list}}
<td>{{this.createdAt}}</td>
<td>{{this.user}}</td> //i am seeing this.user for example - **5ef9fb54f4bb8dff810104f7**
<td>
{{#ifEqual this.user looged_user_id }} //looged_user_id coming from req.user._id.toString()
<a href="/tracker/{{this._id}}"> Edit </a>
<a href="/tracker/delete/{{this._id}}" onclick="return confirm('Are you sure to delete this record ?');"> Delete
</a>
{{else}}
<a href="#"> Edit </a>
<a href="#" onclick="return confirm('Are you sure to delete this record ?');"> Delete
</a>
{{/ifEqual}}
</td>
</tr>
{{/each}}
请指导我如何比较两个ID。
在您的代码中,您需要首先将looged_user_id传递给模板,然后只有它才会进入您的helper函数。
请访问http://tryhandlebarsjs.com/
模板:
{{#each list}}
<td>{{this.createdAt}}</td>
<td>{{this.user}}</td>
<td>
{{#ifCond this.user}} //Here 1 is just hardcoded insted of that need to change with actal variable
<a href="/tracker/{{this._id}}"> Edit for if </a>
<a href="/tracker/delete/{{this._id}}" onclick="return confirm('Are you sure to delete this record ?');"> Delete looged_user_id
</a>
{{else}}
<a href="#"> Edit for else </a>
<a href="#" onclick="return confirm('Are you sure to delete this record ?');"> Delete
</a>
{{/ifCond}}
</td>
</tr>
{{/each}}
上下文:
{
"list": [{
"user": 1,
"content": "hello"
},{
"user": 2,
"content": "world"
}],
}
注册助手函数:
Handlebars.registerHelper('ifCond', function(v1, options) {
if(v1 === looged_user_id ) {
return options.fn(this);
}
return options.inverse(this);
});
结果:
<td></td>
<td>1</td>
<td>
<a href="/tracker/"> Edit for if </a>
<a href="/tracker/delete/" onclick="return confirm('Are you sure to delete this record ?');"> Delete looged_user_id
</a>
</td>
</tr>
<td></td>
<td>2</td>
<td>
<a href="#"> Edit for else </a>
<a href="#" onclick="return confirm('Are you sure to delete this record ?');"> Delete
</a>
</td>
</tr>