2017-09-06 32 views
0

我是NodeJSExpressJS的新手。我想创建自定义for循环遍历从NodeJS数据通过index像我们正在使用的不是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循环?

任何人都可以帮助我创建新的帮手功能吗?

+0

你创建的'for'辅助函数有什么问题?为什么你想创建另一个? –

+0

我想从视图 –

+0

这样做'for(index = 0; index

回答

1

你需要为了使用你的循环内的index值使用{{@key}}

例如,

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

希望这有助于!