Search code examples
javascriptnode.jsexpresshandlebars.js

How to create custom for loop in handlebars template


I am new to NodeJS and ExpressJS. I want to create custom for loop for traversing through the from the NodeJS data via index like we are using for not for loop.

Check below code from NodeJS where I am getting all users of role User and passing users to handlebars view.

exports.getAll = function (req, res) {
    models.Users.findAll({
        where: {
            role: {$ne: "User"}
        }
    }).then(users => {
        return res.render('users/index', {users: users});
    }).catch(error => {
        return res.json(error);
    });
};

Checkout my handlebars view. From below code I am able to traverse through all the users, but I don't want to use like that.

I want to use like we are using normal for loop for(index = 0; index < count(users); index++

<table class="table table-hover table-light">
    <thead>
        <tr class="uppercase">
            <th class="col-md-2"> Login </th>
            <th class="col-md-6"> Description </th>
            <th class="col-md-2">  </th>
        </tr>
    </thead>
    <tbody>
        {{#each users}}
        <tr>
            <td> {{username}} </td>
            <td> {{about_me}} </td>
            <td>
                <button type="button" id="#basic" data-toggle="modal" href="#basic" class="btn btn-blue btn-xs">Edit</button>
                <button type="button" class="btn btn-danger btn-xs">Remove</button>
            </td>
        </tr>
        {{/each}}
    </tbody>
</table>

I tried creating helper function. Check below code

hbs.registerHelper('for', function(from, to, incr, block) {
    var accum = '';
    for(var i = from; i < to; i += incr)
        accum += block.fn(i);
    return accum;
});

Is it possible to create normal for loop in handlebars template engine?

Can anyone help me to create new helper function?


Solution

  • You need to use {{@key}} in order to use the index value inside your loop,

    For example,

    <tbody>
        {{#each users}}
        <tr>
            <td> {{username}} - {{@key}} </td>
        </tr>
        {{/each}}
    </tbody>
    

    Hope this helps!