Search code examples
javascriptnode.jsexpresshandlebars.js

calling function prototype in handlebars


I built a simple app using express and handlebars

in my models, I have function prototype like this

// myModel.js
Student.prototype.getFullname = function () {
  return `${this.first_name} ${this.last_name}`;
}

in my router, I can invoke the function prototype like this

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

my question: how to call a function prototype in handlebars?

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

Solution

  • In handlebars helpers docs, there's literally your example, with the fullName helper.

    Registering helper:

    Handlebars.registerHelper('getFullName', function(student) {
    
        return `${student.first_name} ${student.last_name}`;
    
    });
    

    Using helper:

    {{#each this}}
        <tr>
          <td>{{ id }}</td>
          <td>{{ first_name }}</td>
          <td>{{ last_name }}</td>
          <td>{{ getFullName this }}</td>
        </tr>
    {{/each}}