[英]How to create custom for loop in handlebars template
我是NodeJS
和ExpressJS
新手。 我想创建自定义的for
循环,以便通过index
遍历NodeJS
数据,就像我们正在使用for 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
循环?
谁能帮我创建新的助手功能?
您需要使用{{@key}}
才能在循环中使用index
值,
例如,
<tbody>
{{#each users}}
<tr>
<td> {{username}} - {{@key}} </td>
</tr>
{{/each}}
</tbody>
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.