【问题标题】:How to create custom for loop in handlebars template如何在车把模板中创建自定义 for 循环
【发布时间】:2017-09-06 06:54:51
【问题描述】:

我是NodeJSExpressJS 的新手。我想创建自定义的for 循环,以便通过index 遍历来自NodeJS 的数据,就像我们使用的不是for 循环一样。

检查来自NodeJS 的以下代码,我在其中获取角色User 的所有用户并将用户传递给handlebars 视图。

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

查看我的车把视图。从下面的代码中,我可以遍历所有用户,但我不想那样使用。

我想像我们使用普通的一样使用for循环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>

我尝试创建辅助函数。检查下面的代码

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

是否可以在handlebars模板引擎中创建正常的for循环?

谁能帮我创建新的辅助函数?

【问题讨论】:

  • 您创建的for 辅助函数有什么问题?为什么要创建另一个?
  • 我想做for(index = 0; index &lt; count(users); index++)这样的视图
  • 你的意思是代替#each ?
  • 是的,我想要每条记录的索引
  • 考虑到 users 在您的情况下是一个对象,您可以尝试将 {{@key}} 放在您的 #each 块中吗?

标签: javascript node.js express handlebars.js


【解决方案1】:

您需要使用{{@key}} 才能在循环中使用index 值,

例如,

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

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2020-07-18
    • 1970-01-01
    • 2021-02-19
    • 2017-01-05
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    相关资源
    最近更新 更多