在车把中调用函数原型

问题描述 投票:0回答:2

我使用 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}}
javascript node.js express handlebars.js
2个回答
1
投票

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}}

0
投票

如果需要,可以使用通用助手来运行带参数的方法?

helpers.js

Handlebars.registerHelper('run', function(func, method)
{
    return func[method].apply(null, Array.prototype.slice.call(arguments, 2));
});

车把代码

      {{run rows[0] getFullName}}
© www.soinside.com 2019 - 2024. All rights reserved.