【发布时间】:2017-09-06 06:54:51
【问题描述】:
我是NodeJS 和ExpressJS 的新手。我想创建自定义的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 < count(users); index++)这样的视图 -
你的意思是代替
#each? -
是的,我想要每条记录的索引
-
考虑到
users在您的情况下是一个对象,您可以尝试将{{@key}}放在您的#each块中吗?
标签: javascript node.js express handlebars.js