【问题标题】:calling function prototype in handlebars在车把中调用函数原型
【发布时间】:2017-11-04 09:42:59
【问题描述】:

我使用 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}}

【问题讨论】:

  • 为什么不让full_name 成为吸气剂? Object.defineProperty(Student.prototype, "full_name", {get(){ return this.first_name + " " + this.last_name }})class Student { get full_name(){ return ... }}
  • 这是我在训练营中得到的要求。我在这里做任务
  • 然后您可以注册一个帮助您调用该方法的助手。
  • 我现在不明白helper,你能给我一些线索吗?

标签: javascript node.js express handlebars.js


【解决方案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}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2023-04-09
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多