我使用 Express 和车把构建了一个简单的应用程序
在我的模型中,我有这样的函数原型
// myModel.js
Student.prototype.getFullname = function () {
return `${this.first_name} ${this.last_name}`;
}
在我的路由器中,我可以像这样调用函数原型
// myRouter.js
const rows = await Model.Student.findAll();
console.log(rows[0].getFullname()); // I can invoke function prototype here
res.render('mypage', rows); // with express, render it to hbs
我的问题:如何在车把中调用函数原型?
{{#each this}}
<tr>
<td>{{ id }}</td>
<td>{{ first_name }}</td>
<td>{{ last_name }}</td>
<td>{{ rows[0].getFullname() }}</td> // I wanna call it here
</tr>
{{/each}}
在 handlebars helpers docs 中,确实有您的示例,以及
fullName
帮助器。
注册助手:
Handlebars.registerHelper('getFullName', function(student) {
return `${student.first_name} ${student.last_name}`;
});
使用助手:
{{#each this}}
<tr>
<td>{{ id }}</td>
<td>{{ first_name }}</td>
<td>{{ last_name }}</td>
<td>{{ getFullName this }}</td>
</tr>
{{/each}}
如果需要,可以使用通用助手来运行带参数的方法?
helpers.js
Handlebars.registerHelper('run', function(func, method)
{
return func[method].apply(null, Array.prototype.slice.call(arguments, 2));
});
车把代码
{{run rows[0] getFullName}}